jQuery fallback for HTML5 placeholder attribute

August, 21 2011

If you google placeholder and jQuery you quickly find some handy code for a javascript fallback for the HTML5 placeholder functionality:

https://gist.github.com/379601

If you want to read more check out the blog post.

As written this will always override the built in browser behaviour, and it isn't as good as the built in behaviour. We only want this code to be registered if the current browser doesn't natively support placeholder, fortunately detection is easy thanks to Dive Into HTML5

http://diveintohtml5.org/everything.html#placeholder

This leads to this combination of code:

if  (!('placeholder' in document.createElement('input')) || !('placeholder' in document.createElement('textarea'))) {
    $(document).ready( function() {
        $('[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('');
            }
          })
        });
    });
}

The code makes the somewhat broad assumption that no browser supports placeholder for an input but not for a textarea, or if it did, the behaviour shouldn't be overridden. Part of the appeal for HTML5 for me is the ability to provide great user experience for those on modern browser and good experiences on those forced not to upgrade.


Tweet comments, corrections, or high fives to @amjoconn