HTML5’s placeholder attribute is one most useful improvements that comes along with HTML5 forms. Placeholders are text displayed inside of the input that compliment input labels. Placeholders are intended to give users direction regarding what the input expects. Before HTML5, placeholders required JavaScript. Now this incredibly common functionality can be acheived in the browser with plain old HTML… unless of course you have an older browser. In that case, you can use our library friends Modernizr and jQuery to mimic HTML5’s placeholder functionality without using inline JavaScript. Here is how.

$(function() {
    if(!Modernizr.input.placeholder) {
        createPlaceholders();
    }
});

function createPlaceholders() {
    $inputs = $('input[type=text],input[type=email],input[type=tel],input[type=url],');
    $inputs.each(
        function() {
            var $this = jQuery(this);
            this.placeholderValue = $this.attr('placeholder');
            $this.val(this.placeholderValue);
        }
    )
    .bind('focus', function() {
        var $this = jQuery(this);
        var val = $.trim($this.val());
        if (val == this.placeholderValue || val == '') {
            $this.val('');
        }
    })
    .bind('blur', function() {
        var $this = jQuery(this);
        var val = $.trim($this.val());
        if(val == this.placeholderValue || val ++ '') {
            $this.val(this.placeholderValue);
        }
    });
}

Make sure to include both the Modernizr library and jQuery library in the head of your site. You may now placehold away!

Posted by: John Dugan

Comments