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.

1<script src="/Scripts/Libs/jquery-1.8.2.js" type="text/javascript"> </script>
2<script src="/Scripts/Libs/modernizr-1.7.min.js" type="text/javascript"> </script>

placeholder

1jQuery(function () {
2 // check placeholder browser support
3 if (!Modernizr.input.placeholder) {
4 // set placeholder values
5 jQuery(this).find('[placeholder]').each(function () {
6 if (jQuery(this).val() == '') // if field is empty
7 {
8 jQuery(this).val(jQuery(this).attr('placeholder')); jQuery(this).addClass('placeholder'); } });
9 // focus and blur of placeholders
10 jQuery('[placeholder]').focus(function () {
11 if (jQuery(this).val() == jQuery(this).attr('placeholder')) {
12 jQuery(this).val('');
13 jQuery(this).removeClass('placeholder');
14 }
15 }).blur(function () {
16 if (jQuery(this).val() == '' || jQuery(this).val() == jQuery(this).attr('placeholder')) {
17 jQuery(this).val(jQuery(this).attr('placeholder'));
18 jQuery(this).addClass('placeholder');
19 }
20 });
21 // remove placeholders on submit
22 jQuery('[placeholder]').closest('form').submit(function () {
23 jQuery(this).find('[placeholder]').each(function () {
24 if (jQuery(this).val() == jQuery(this).attr('placeholder')) {
25 jQuery(this).val('');
26 }
27 });
28 });
29 }
30});

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

1/*Modernizr fall back style for placeholder*/
2 .placeholder {
3 color:lightgray;
4 font-style: italic;
5}

Here is how to use it.

1<input type="text" placeholder="This is a placeholder text"/>

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.