Using jQuery, we can easily hide and restore the placeholder when the user clicks on the field

you can use jQuery to hide the placeholder when a user focuses on a field and restore it when they blur (leave) the field. Here's an example:

Input field HTML: 

1
<input id="nameField" type="text">

jQuery Code:

1
2
3
4
5
6
7
8
9
10
11
12
$(document).ready(function () {
    const $input = $('#nameField');
 
    $input.on('focus', function () {
        $(this).data('placeholder', $(this).attr('placeholder')); // Save placeholder
        $(this).attr('placeholder', ''); // Remove placeholder
    });
 
    $input.on('blur', function () {
        $(this).attr('placeholder', $(this).data('placeholder')); // Restore placeholder
    });
});

Explanation

Focus Event:

  • Triggered when the input field is clicked or gains focus.
  • Save the current placeholder value in a custom data attribute (data('placeholder')) and clear the placeholder.

Blur Event:

  • Triggered when the input field loses focus.
  • Restore the placeholder from the saved data attribute.

No comments:

Post a Comment