HTML5 and input placeholders with a fallback

April 2, 2012 |

HTML5 is making coding easier.  No other way to say it.  In the past to create default text in an <input> field you had to do a bunch of different hacks or background image swapping… Now you can do this following:

<input type="text" />

“My Placeholder Text” is the text presented to the end user.  Different web browsers handle the attribute differently but when the end user begins typing, the text disappears and is replaced with whatever text they are typing.

This solution is great except we still have to account for IE7/8/9 (seriously how is IE’s unreleased browsers the only one that may support html5.  How behind the times is Redmon), Older FF, Safari and Chrome.   To make this work with those browsers I employ a Modernizr.  Simple go to Modernizr, click to build your own Production code.  In this case we only need Input Attributes.  Finally to bring it all together I used a cool little bit of code from This Guy, to make it all work.

/**
 * HTML5 Placeholder Text jQuery Fallback with Modernizr
 *
 * @url http://uniquemethod.com/
 * @author Unique Method
 */
jQuery(function()
{
 // check placeholder browser support
 if (!Modernizr.input.placeholder)
 {

 // set placeholder values
 jQuery(this).find('[placeholder]').each(function()
 {
 if (jQuery(this).val() == '') // if field is empty
 {
 jQuery(this).val( jQuery(this).attr('placeholder') );
 }
 });

 // focus and blur of placeholders
 jQuery('[placeholder]').focus(function()
 {
 if (jQuery(this).val() == jQuery(this).attr('placeholder'))
 {
 jQuery(this).val('');
 jQuery(this).removeClass('placeholder');
 }
 }).blur(function()
 {
 if (jQuery(this).val() == '' || jQuery(this).val() == jQuery(this).attr('placeholder'))
 {
 jQuery(this).val(jQuery(this).attr('placeholder'));
 jQuery(this).addClass('placeholder');
 }
 });

 // remove placeholders on submit
 jQuery('[placeholder]').closest('form').submit(function()
 {
 jQuery(this).find('[placeholder]').each(function()
 {
 if (jQuery(this).val() == jQuery(this).attr('placeholder'))
 {
 jQuery(this).val('');
 }
 })
 });

 }
});

Leave a Reply