Code Responsible

Skip navigation

HTML5 Placeholder Text in IE

An example of placeholder text in search fieldOne of the great additions HTML5 has brought us is the ability to simply add placeholder text to our input fields. The placeholder text is displayed in the input box when it is empty to help describe to the user what to enter. Once the user focuses on that particular input, the text will clear allowing the user to input the proper text.

Unfortunately the placeholder feature isn’t supported by all browsers. There is an easy way to leverage JQuery and Modernizr to create a fallback for any of the legacy browsers that don’t support placeholder text.

Modernizr will check to see if the browser supports placeholder and if it doesn’t the JQuery code will run creating a fallback for the placeholder text.

Here’s a code snippet you can add to your HTML that will use Modernizr to help legacy browsers support placeholder text. You’ll also need to download Modernizr and add it to your your site. (make sure to change the path to where you’ve placed the Modernizr script)

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="js/modernizr.js"></script>

<script>
$(document).ready(function(){

if(!Modernizr.input.placeholder){

    $('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });

}
</script>

Source: Hagenburger

41 Posts

Ryan Burgess

Ryan Burgess is a Manager, UI Engineering at Netflix in San Francisco, California. Previously at Evernote. Listen to Ryan on the Front End Happy Hour podcast. He's also the creator of SensesLost.com, an online-based arts and culture magazine that focuses on graffiti and tattoo art.

20 Responses to “HTML5 Placeholder Text in IE”

Leave a Reply

Comment Form