Clear Input Placeholder On Focus Using jQuery

November 22nd, 2015 - Posted by Steve Marks to (X)HTML / CSS, Javascript / jQuery, Web Development.

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.

This entry was posted on Sunday, November 22nd, 2015 at 4:54 pm by +Steve Marks and is filed under (X)HTML / CSS, Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first