Create a dynamic animation effect for the placeholder in an input field that triggers when the user starts typing

Have you ever come across interactive demos like this one?

I've noticed that most examples involve creating a new element.

parent().append("<span>" + $input.attr('placeholder') + "</span>");

Is there a way to make the placeholder text disappear with an animation when the user interacts with the input field, without having to add a new element dynamically?

$("input[placeholder]").each(function () {
    
    var $input = $(this);
    // wrap the input with a label
    $input.wrap("<label class='placeholder'>");
    // append a span to the label
    $input.parent().append("<span>" + $input.attr('placeholder') + "</span>");
    // and finally remove the placeholder attribute
    $input.attr('placeholder', '');
    
}).keyup(function () {
    
    var $input = $(this);
    // toggle hidden class on span, depending on whether there is content or not
    if ($input.val() === "") {
        $input.next("span").removeClass("hidden");
    } else {
        $input.next("span").addClass("hidden");
    }
});
label.placeholder {
    position: relative;
}

label.placeholder span {
    opacity: 1;
    -webkit-transition: opacity 250ms;
    -moz-transition: opacity 250ms;
    -o-transition: opacity 250ms;
    -ms-transition: opacity 250ms;
    transition: opacity 250ms;
    position: absolute;
    left: 5px;
    top: 2px;
    font-size: 12px;
    color: grey;
}

label.placeholder span.hidden {
    opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="the placeholder">

Answer №1

Is there a method to animate the disappearance of a placeholder upon input without adding a new element?

Given the challenge of styling default browser pseudo elements like ::-webkit-input-placeholder/::-moz-placeholder, :-ms-input-placeholder across different browsers, using a :before or :after pseudo element as a substitute for the appended span element is recommended. Nevertheless, since pseudo elements cannot be added directly to input elements, wrapping the input element would still be necessary.

Check out the Updated Example

The pseudo element is absolutely positioned relative to its parent to cover the parent element. The value of the pseudo element's content is determined by a custom data-* attribute in the wrapper element, specifically data-placeholder, which is set using attr(data-placeholder).

I also made your jQuery script a bit simpler:

$('input[placeholder]').each(function () {
    $(this).wrap('<label class="placeholder" data-placeholder="' + this.placeholder + '">').attr('placeholder', '');
}).on('keyup', function () {
    $(this).parent().toggleClass('hidden', this.value !== '');
});
label.placeholder {
    position: relative;
}
label.placeholder:after {
    content: attr(data-placeholder);
    position: absolute;
    top:0; right: 0;
    bottom: 0; left: 0;
    padding: 2px;
    font-size: 12px;
    color: grey;
    cursor: text;
    transition: opacity 250ms;
}
label.hidden.placeholder:after {
    opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="the placeholder"/>

If dealing with lengthy placeholder values, you can also incorporate the following adjustment:

View the Updated Example

label.placeholder:after {
    /* .. */
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

redactor.js: Disable backspace functionality when cursor is at the start of a div-container

Currently, I am working with the redactor.js editor that utilizes editable div containers. A challenge I have encountered is when multiple contenteditable containers are nested; deleting content using the backspace button can inadvertently delete the entir ...

Activating the Mobile Menu Function when the Window is Resized

I've developed a JavaScript function that triggers on window resize. When switching between landscape and portrait orientation on mobile devices or tablets, the window dimensions change. This functionality is also useful for browser testing on desktop ...

Issue with PHP/MySQL registration page failing to save user information to database

As I work on developing my website that includes user registration and login functionality, I encountered an issue where the registration page was not loading properly. Initially, the registration process worked perfectly, but the next day, upon trying to ...

I'm facing a challenge with retrieving the controller's scope in my Angular directive

Having trouble accessing the settings I receive from the server in my app. The directives are set up correctly and the $http is used to fetch a js file with the app settings. However, despite being able to log the scope in the console, I am unable to acces ...

Integrating Dart with external libraries

Here is a straightforward example demonstrating the usage of a map library: <!doctype html> <html> <head> <script src="http://api4.mapy.cz/loader.js"></script> <script>Loader.load()</script> </head; &l ...

Animated CSS image swap triggered by hovering over and moving away from an element

I just started learning about jQuery yesterday, so I'm struggling a bit. But I have an idea in mind - I want to swap the image of my logo when the mouse hovers over it. Here's the code I've come up with so far, although I know it's not ...

Looking to update the URL from another component?

My current project is using Angular 6 and I am working on creating a list of buttons on the left panel such as "Ice cream", "Pop corns", and more. The goal is for users to click on these buttons which will then change the URL of the add button located in t ...

Utilizing Node.js and Express alongside EJS, iterating through objects and displaying them in a table

Today I embarked on my journey to learn Node.js and I am currently attempting to iterate through an object and display it in a table format. Within my router file: var obj = JSON.parse(`[{ "Name": "ArrowTower", "Class" ...

When using JavaScript with React, setting a value after the onBlur event can result in users having to click

In my React form, I have an input button with an onBlur event that sets the value to a useState property. However, after the onBlur event is triggered, the user has to click the button twice to focus on it properly. It seems like the page needs time to pro ...

Using jQuery to adjust the length of a string to fit within a specific width

I am working with a table and need to input strings in each cell, but they are wider than the cell width. I want to shorten the strings without breaking lines, and add '...' at the end to show that the string is long. The table consists of aroun ...

Suggestions for incrementing a button's ID every time it is clicked

I am working on a button functionality that increases the button id when clicked. Below is the HTML code for the button: <input type="button" id="repeataddon-1" name="repeataddon" class="repeataddon" value="add" > Accompanied by the following scr ...

Steps for removing a chosen file from several input files by clicking a button

Within my application, there is an input file that displays a list of selected files underneath it. Each of these selected files has a corresponding remove button. While I am able to successfully remove a single file with ease, I struggle when attempting t ...

Encountering npm error code ERR_SOCKET_TIMEOUT while attempting to generate a React application

Every time I attempt to create a React app using the command: npx create-react-app chat-app I encounter this error message: Error I have attempted various solutions in an effort to resolve the error: To check if I am behind a proxy, I ran the following ...

Vue(x) causing state mutation in array

I'm currently in the process of building a Vue application to help me learn more about web development. I've hit a roadblock when it comes to updating an array in my state with data from an API. Here's a snippet of the API response: { "st ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

The TypeScript compiler does not allow a 'number' type to be assigned to 0, 10, or 20, even when the number itself is 0

When testing out my code snippet on the playground for Typescript, an error appears on line 24. I discovered that the issue can be resolved by explicitly casting commands back to <IPlan[]>, but I wonder why this extra step is necessary. Property &a ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

Utilizing PHP to create a form via email

I have created this form and I would like to know if it is secure enough. I attempted multiple times to implement a captcha system, but unfortunately, it did not work for me. As I am still a student, please refrain from sending overly complex solutions. Q ...

Learn how to update a fixed value by adding the content entered into the Input textfield using Material-UI

I made a field using the Input component from material-ui: <Input placeholder="0.00" value={rate} onChange={event => { this.setState({ `obj.rate`, event.target.value }); }} /> Whenever I input a rate into this field, ...

Having trouble getting CSS media query to work in my Rails mailer template

Is it true that media queries do not work in email templates? I have a simple test template and a query BUT can't seem to get it to function properly. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DT ...