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 to find help quickly from experienced JavaScript freelance developers.
Follow me for updates
I share all new blog posts on Twitter and Facebook.
When I'm not coding
My wife and I are attempting to ride motorcycles around Australia and vlog about it on YouTube.