May 08 2012

Add HTML5 placeholder support to older browsers

This is a handy javascript function that I use on a lot of my sites to ensure that the html5 placeholder attribute is supported by older browsers.

Just paste it as is and your site will automagically support the placeholder attribute in all browsers.

function ensurePlaceholderSupport()
{
    var input = document.createElement('input');
    if (!('placeholder' in input))
    {
        // add support for html5 placeholder attribute
        $('input[type="text"]').each(function ()
        {
            $(this).focus(function ()
            {
                if ($(this).attr('value') === $(this).attr('placeholder'))
                {
                    $(this).attr('value', '');
                }
            }).blur(function ()
            {
                if ($(this).attr('value') === '')
                {
                    $(this).attr('value', $(this).attr('placeholder'));
                }
            }).blur();
        });

        // remove placeholder text when submit button is clicked
        $('form button[type="submit"]').click(function ()
        {
            $(this).closest("form")
            .find('input[type="text"]')
                .each(function ()
                {
                    if ($(this).attr('value') === $(this).attr('placeholder'))
                    {
                        $(this).attr('value', '');
                    }
                });
        });

        // re-add placeholder text if validation failed 
        // (only required if jquery validation plugin is being used)
        $('form').submit(function ()
        {
            if (!$(this).valid())
            {
                $(this).find('input[type="text"]')
                .each(function ()
                {
                    if ($(this).attr('value') === '')
                    {
                        $(this).attr('value', $(this).attr('placeholder'));
                    }
                });
            }
        });
    }
}

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

 


Sponsored by