Clear Input Placeholder On Focus Using jQuery
The placeholder component of textfields in HTML is a great way to provide the user with a hint on what should be entered, or to remove the need for labels altogether.
The default behaviour in some browsers (Chrome, Safari etc) is to leave the placeholder showing until the user starts entering text. Even when the input is focused the placeholder will still show.
Recently a client wanted us to remove the placeholder as soon as someone clicks in the box and gives it focus. Not being default browser behavior, I wrote a little bit of jQuery to fulfil the clients requests:
jQuery(document).ready(function() { jQuery('input').each(function() { if (jQuery(this).attr('placeholder') && jQuery(this).attr('placeholder') != '') { jQuery(this).attr( 'data-placeholder', jQuery(this).attr('placeholder') ); } }); jQuery('input').focus(function() { if (jQuery(this).attr('data-placeholder') && jQuery(this).attr('data-placeholder') != '') { jQuery(this).attr('placeholder', ''); } }); jQuery('input').blur(function() { if (jQuery(this).attr('data-placeholder') && jQuery(this).attr('data-placeholder') != '') { jQuery(this).attr('placeholder', jQuery(this).attr('data-placeholder')); } }); });
The above will not only remove the placeholder when the box is focuses, but will also reenter the placeholder when the user clicks away and hasn’t entered anything.
No comments have been left yet. Be the first