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, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some JavaScript Help?
Search fiverr to find help quickly from experienced JavaScript developers.