yama-dev
9/23/2011 - 12:56 AM

HTML5 Placeholder Polyfill using jQuery

HTML5 Placeholder Polyfill using jQuery

(function ($) {

    $(function () {
        if (!supportsInputAttribute('placeholder')) {
            $('[placeholder]').each(function () {
                var $this = $(this),
                    $form = $this.closest('form'),
                    placeholderText = $this.attr('placeholder'),
                    placeholderColor = 'GrayText',
                    defaultColor = $this.css('color');
                $this.bind({
                    focus: function () {
                        if ($this.val() === placeholderText) {
                            $this.val('').css('color', defaultColor);
                        }
                    },
                    blur: function () {
                        if ($this.val() === '') {
                            $this.val(placeholderText).css('color', placeholderColor);
                        } else if ($this.val() === placeholderText) {
                            $this.css('color', placeholderColor);
                        }
                    }
                });
                $this.trigger('blur');
                $form.submit(function () {
                    if ($this.val() === placeholderText) {
                        $this.val('');
                    }
                });
            });
        }
    });

    // detect support for input attirbute
    function supportsInputAttribute (attr) {
        var input = document.createElement('input');
        return attr in input;
    }

})(jQuery);