HTML5 Placeholder in IE and Unsupported Browsers

December 9th, 2011
By: Cory Mathews

The html5 placeholder attribute on an input tag is a really nice, however easily adding that feature to older IE versions and any other browsers that don’t support it renders it unusable in production.

The below javascript/jquery code will check the page for any inputs with the placeholder attribute and make it work in browsers that do not support it, and it will do nothing in those that do.

(function($) {
  $.fn.placeholder = function() {
    if(typeof document.createElement("input").placeholder == 'undefined') {
      $('[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().parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
          var input = $(this);
          if (input.val() == input.attr('placeholder')) {
            input.val('');
          }
      })
    });
  }
}
})(jQuery);

Line 3 of the javascript checks if the browser supports the placeholder attribute and only runs if it does not.

To call this plugin just add the following to your page.

$.fn.placeholder();

You may also want to add the following css to make it more like the browsers that do support it.

.placeholder { color: #aaa; }

The original bulk of this code was written by Nico Hagenburger. I basically only added the support check and turned it into a plugin.