Home » Html » Clear HTML5 placeholder attribute text on focus in Chrome

Clear HTML5 placeholder attribute text on focus in Chrome

Posted by: admin December 31, 2017 Leave a comment

Questions:

Is there any way I can clear placeholder text on focus in Chrome, Firefox clears the text on focus but Chrome doesn’t.

This confuses the user whether the text in the bar is typed, or it’s a placeholder text (Even if I changed the text color to light grey), I don’t want to use unnecessary JavaScript or jQuery for this, I want to know if there’s some HTML/CSS solution for this

Demo Fiddle

Chrome Preview (On Focus)

Chrome Preview On Focus

Firefox Preview (On Focus)

Firefox Preview On Focus

Answers:

Try using

input:focus::-webkit-input-placeholder 
{
    color: transparent;
}

It will resolve the issue. The text is visible on focus because of the auto focus on page load.

Questions:
Answers:

Now firefox works in other way, so I used this code:

input:focus::-webkit-input-placeholder{
    color: transparent!important;
}
input:focus::-moz-placeholder{
    color: transparent!important;
}
input:focus:-moz-placeholder{
    color: transparent!important;
}

Questions:
Answers:

This is how chrome handles it, and chrome users will probably expect it to be handled like this. You could, however, use jQuery to remove the “placeholder” attribute when it is focused on.

I found an apparent fix for you, from a google group @ https://github.com/mathiasbynens/jquery-placeholder/issues/51#issuecomment-4193018

// Fixing Webkit that not clearing input/textarea when get focus
$(function(){
  if ($.browser.webkit) {
    $('input, textarea').on('focus',function(){
      if ( $(this).attr('placeholder') ) $(this).data('placeholder', $(this).attr('placeholder')).removeAttr('placeholder');
}).on('blur', function(){
        if ( $(this).data('placeholder') ) $(this).attr('placeholder', $(this).data('placeholder')).removeData('placeholder');
    });
  }
});

Questions:
Answers:

I found that the Shubhanshu’s solution didn’t work for me, but I did find this on CSS tricks that did work in Chrome, doesn’ seem to work in FF though.

[placeholder]:focus::-webkit-input-placeholder {
  color: transparent;
}