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: 2012-12-19

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.

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

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.

<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.