How to create a fall back to html5 placeholder for Internet Explorer with Modernizr library<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to create a fall back to html5 placeholder for Internet Explorer with Modernizr library

Posted on: December 19, 2012

Modernizr is a small javascript library that work in parallel of your main library (like JQuery) and make work more advanced features like some CSS3 features or Html5 features on browser that doesn't support it nativly.

One feature that even Internet Explorer 10 doesn't handle is the attribute placeholder. Modernizr let you check if the current browser support it, if not create your own custom fall back.

Once you added the Modernizr library to your webpage, you can now create a new javascript file with a function that will test the placeholder feature, if it's not available will execute some custom code.

placeholder

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')); jQuery(this).addClass('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(''); } }); }); } });

You can also set a class to style the text when it's in a placeholder mode.

/*Modernizr fall back style for placeholder*/ .placeholder { color:lightgray; font-style: italic; }

Here is how to use it.

That's it, you have now the placeholder feature available for all browser. You only need to use it as you would if the user would have used a more recent browser.