Tuesday 20 September 2011

HTML5 Placeholder in all browsers

One of my favourite features of HTML5 (and yes, I have several!) is the placeholder attribute. It's fantastic for useability and reduces the amount of space used by forms on the page.

And of course, it's not supported by Internet Explorer.

Because I was building a form that requires placeholder text,and validation (what forms don't these days) I decided to finally do something about it.

So here is a little jQuery snippet I wrote to add in support for browsers that don't natively work with the placeholder attribute. It also works in both input and textarea fields.

I've used Modernizr to check for placeholder support. Why re-write the wheel?

// Add pseudo placeholder to bad browsers
    var noPlaceSupport = !Modernizr.input.placeholder;
 
    if(noPlaceSupport) {
        var myInputs = $('input[placeholder], textarea[placeholder]');
        myInputs.each(function() {          
            // Set a value now!
            $(this).val($(this).attr('placeholder'));
            // Set up my focus in, to remove text if it is the placeholder
            $(this).focusin(function() {
                if($(this).val() == $(this).attr('placeholder')) {
                    $(this).val('');
                }
            });
            // On focus out, if empty set it back to the placeholder
            $(this).focusout(function() {
                if ($(this).val() == '') {
                    $(this).val($(this).attr('placeholder'));
                }
            });
        });
    }
There is one little gotcha with this; I had originally written the check as $(this).placeholder, as I figured jQuery was smart enough to work with that in IE. Sadly I was mistaken, but $(this).attr('placeholder') is cross browser compatible.

And now you can extend your validation plugin to check for the default value!

Of course, there is no great fallback here for no JS browsers. Personally, if I had more time I would be using jQuery to dynamically make the placeholder text the label value for this field, and then hiding the label.

I hope this snippet is of use to someone out there!

No comments:

Post a Comment