Search code examples
htmljqueryshow-hideplaceholder

Check if text is being entered in input using Javascript/jQuery


I am trying to hide a placeholder while the input is being used and while there's text inside the input. Here's a simplified version of the HTML for the input and placeholder:

<div id="search-placeholder"><span class="fa fa-search"></span>&nbsp; Search</div>
<input id="search-input" type="text" name="search" />

I tried using jQuery but it does not return the desired result:

$(document).ready(function(){
  $('#search-input').focus(function(){
    $('#search-placeholder').fadeOut(100);
  }).focusout(function(){
    $('#search-placeholder').fadeIn(100);
  });
});

The placeholder will hide when the input is selected, as it should. But it will show again when the user clicks elsewhere, even while the input is not empty! The placeholder is visible on top of the input value, so I tried a different approach:

$('#search-input').change(function(){
  if($('#search-input').val() = '') {
    $('#search-placeholder').fadeIn(100);
  }else{
    $('#search-placeholder').fadeOut(100);
  }
})

Unfortunately, this only works when the user clicks elsewhere. The placeholder still shows while typing and while the input is selected, again showing itself on top of the input value. How do I hide <div id="search-placeholder"> while <div id="search-input"> is not empty, or when the input is selected by clicking or tapping it (on focus)?


Solution

  • Maybe try to check the value of the input in the focusout event and only show the placeholder if it's empty:

    $(document).ready(function(){
      $('#search-input').focus(function(){
        $('#search-placeholder').fadeOut(100);
      }).focusout(function(){
        if($('#search-input').val() === '')
        {
          $('#search-placeholder').fadeIn(100);
        }
      });
    });
    

    I think you could extract the $('#search-input') and $('#search-placeholder') elements to variables, so the code becomes a bit more readable.