jQuery: making the placeholder HTML5 attribute work across browsers

jQuery: making the placeholder HTML5 attribute work across browsers

How to make the HTML5 placeholder attribute work across browsers by emulating its behavior with jQuery.

Internet Explorer 8 doesn't support the HTML5 placeholder attribute. Fortunately, we can emulate this attribute with jQuery. Let's see how.

We have to create a plugin which will exactly position a wrapper element with its text label just over the selected text field:


(function ($) {
    $.fn.placeholder = function (options) {

        var defaults = {
            text: 'Placeholder'
        };
        options = $.extend(defaults, options);

        return this.each(function () {
            var that = $(this);
            var top = that.offset().top;
            var left = that.offset().left;
            $('<span class="placeholder"/>').text(options.text).css({
                position: 'absolute',
                top: top,
                left: left
            }).insertAfter(that);
            that.focus(function () {
                that.next('span.placeholder').hide();
            });
            that.blur(function () {
                if (that.val() == '') {
                    that.next('span.placeholder').show();
                }
            });
        });
    };
})(jQuery);

We use the top and left offsets of the text field to position our element. Then we use focus and blur event to hide the placeholder while an user is typing and to show it again when the field's value is empty, respectively.

An example:


$(function () {
    $('#text', '#form').placeholder({
        text: 'Lorem'
    });
    $('#text2', '#form').placeholder({
        text: 'Lorem ipsum'
    });
});

[view-example url="http://jsfiddle.net/gabrieleromanato/DtP8N/"]