Published: 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'));
                    }
                });
            }
        });
    }
}

 


Need Some JavaScript Help?

Search fiverr for freelance JavaScript developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by