How to Auto-Hide a Placeholder Text on Focus with CSS and jQuery

The placeholder attribute describes the expected value of an input field. Before entering a value, a short hint is displayed in the field. One of the difficulties concerned with a placeholder text is making it auto-hide upon focus.

To find a solution to this, we suggest you read our snippet. We’ll demonstrate how to make a placeholder text auto-hide upon focus using HTML, CSS, and jQuery.

The simplest way of auto-hiding a placeholder text upon focus is using the onfocus and onblur events with the <input> element. This is quite easy if you follow the steps below.

Create HTML

  • Use an <input> element with the type attribute.
  • Add a placeholder attribute.
  • Add the onfocus and onblur events.

Example of auto-hiding the placeholder text with HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <input type="text" placeholder="enter your text" 
           onfocus="this.placeholder=''" 
           onblur="this.placeholder='enter your text'" />
  </body>
</html>

In the next example, we use the :focus pseudo-class and ::placeholder pseudo-element.

Example of auto-hiding the placeholder text with CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input:focus::placeholder {
        color: transparent;
      }
    </style>
  </head>
  <body>
    <input type="text" placeholder="Enter your text">
  </body>
</html>

Result

Example of auto-hiding the placeholder text with CSS and jQuery:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      li {
        padding: 15px;
      }
      input {
        padding: 8px;
      }
    </style>
  </head>
  <body>
    <form>
      <ul class="field-set field-set-stacked">
        <li class="field field-text">
          <input type="text" placeholder="Enter your name" />
        </li>
        <li class="field">
          <input type="text" placeholder="Enter your email address" />
        </li>
        <li class="field">
          <input type="text" placeholder="Enter your phone number" />
        </li>
      </ul>
    </form>
    <script>
      $("input")
        .each(
          function() {
            $(this)
              .data('holder', $(this)
                .attr('placeholder'));
            $(this)
              .focusin(function() {
                $(this)
                  .attr('placeholder', '');
              });
            $(this)
              .focusout(function() {
                $(this)
                  .attr('placeholder', $(this)
                    .data('holder'));
              });
          });
    </script>
  </body>
</html>