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

Each time the button is clicked, the settings and values will rotate, creating a new

I'm looking to create a button system that transitions from "unmarked" to "form" and updates the database with each click. I want users to be able to cycle through the buttons, triggering a post request via ajax to update the associated ID in the data ...

Is there a way to consistently trigger the browser.webRequest.onBeforeRequest event in Mozilla Firefox when it is launched via a link?

Hello knowledgeable individuals. I am unable to solve this issue on my own. Here is the add-on I have created: 1) manifest.json: { "manifest_version": 2, "name": "Example", "version": "1.0", "description": "Example", "permissions": [ "tabs" ...

Attempting to store form data in a database using PHP has proven to be unsuccessful in my efforts

I am facing an issue while trying to add HTML form data into the database using PHP. Unfortunately, I am unable to successfully insert the HTML form data into the database and I'm not sure what mistake I might be making in my code. Below is the code ...

Increase the size of the textarea when it is clicked on and revert back to its original size when it

My question revolves around a text area that I am trying to manipulate through jQuery. The desired functionality is to increase the height of the text area whenever someone clicks on it, and decrease the height when clicking anywhere else on the screen. & ...

What is the best way to retrieve data from a fetch request within a GET function?

It seems like a simple issue, but I'm struggling to retrieve information from my "body" when utilizing the get method. I've experimented with various approaches to extract the data, but nothing seems to work. Any guidance would be greatly appreci ...

Tips for ensuring that images fully occupy my carousel slides

I am struggling to make my images fit properly within the slides. Here is the code snippet I have tried along with some screenshots: <div className="relative h-24 w-20 sm:h-44 sm:w-100 md:h-44 md:w-60 flex-shrink-0"> <Carousel showThu ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

The jQuery ajax request functions properly on Internet Explorer but does issues arise when used on Firefox, Chrome, or Opera browsers

I have created a test web page to call a WebApi URL and receive a response. The functionality works perfectly in Internet Explorer, but fails in all other browsers. Below is the jQuery code snippet I am using: $(document).ready(function() { jQuery("# ...

How can I utilize a custom function to modify CSS properties in styled-components?

I am working with styled components and need to set the transform property based on certain conditions: If condition 1 is true, set the value to x. If condition 2 is true, set the value to y. If neither condition is true, set the value to null. Despite ...

Challenge with dynamic parent routes

In my React application, different routes are loaded through various parent URLs. For example: {["/sat/", "/act/", "/gre/", "/gmat/", "/toefl/"].map((path) => ( <Route key={path} path={path ...

Can you explain the distinction between rxjs/observable and the traditional jQuery AJAX approach?

Can you explain the distinction between rxjs/Observables and JQuery in terms of asynchronous functions like $.get()? Are both frameworks considered to be asynchronous and reactive? ...

Having difficulty installing the yarn package from GitHub

I'm attempting to install a GitHub package using yarn. I've tried this process many times before, but I have not been successful with this particular repository: https://github.com/coolwanglu/pdf2htmlEX I have already attempted the following w ...

What might be causing Flex not to function properly on my personalized landing page?

I attempted to create a basic landing page featuring an image background with a logo, button, and a row of 4 images displayed side by side using Flex. However, for some reason, the Flex is not functioning properly for the row of images. Here is the code s ...

CSS margin-left causing issues in Chrome Extension

My current situation is incredibly puzzling, as I am at a loss for what is happening. I developed a Firefox add-on using jQuery and CSS to revamp a website. When attempting to transfer the add-on to Chrome (which was relatively straightforward due to the s ...

Node.js is throwing GitHub API 401 Bad Credentials error, whereas curl is not encountering the

I am attempting to authenticate on Enterprise GitHub using @octokit/rest. When I execute the following Curl command, I receive a list of API URLs: curl -u "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80edf9c0e5ede1e9ecaee3e ...

Obtaining the row number from a query and transferring it to another Google spreadsheet

I'm currently facing a challenge in extracting both cell data and the corresponding row number from a different sheet in Google Sheets. Although I have successfully formulated a query to retrieve all necessary column values, I'm struggling to inc ...

Is there a method in JavaScript to access the object to which a function was originally bound?

I have a curiosity about making the code below function properly, capturing the logging as instructed in the comments. function somePeculiar(func) { var funcThis = undefined; // Instead of undefined, how can we access // ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

Validation of forms using Javascript

I currently have an HTML form with JavaScript validation. Instead of displaying error messages in a popup using the alert command, how can I show them next to the text boxes? Here is my current code: if (document.gfiDownloadForm.txtFirstName.value == &ap ...

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...