HTML5 placeholder attribute for IE9 and prior

One of the many nice features introduced in HTML5 is placeholder attribute for form fields, which is very useful to show helpful hints for the field. This can be done with JavaScript but it’s even better being native to HTML5.

That is, until you use browser that doesn’t support HTML5, like IE9 (and before).

There are quite a few codes out there claiming to make placeholder attribute work in older browsers. But after trying out a few, the following code worked the best (founded via this page).

jQuery and Modernizr are required.

Define CSS:

.placeholder { color: #aaa; } 

The code

<script type="text/javascript">
$(document).ready(function() {

    // Only do anything if the browser does not support placeholders
    if (!Modernizr.input.placeholder) {

        // Format all elements with the placeholder attribute and insert it as a value
        $('[placeholder]').each(function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr('placeholder'));
                $(this).addClass('placeholder');
            }
            $(this).focus(function() {
                if ($(this).val() == $(this).attr('placeholder') && $(this).hasClass('placeholder')) {
                    $(this).val('');
                    $(this).removeClass('placeholder');
                }
            }).blur(function() {
                if($(this).val() == '') {
                    $(this).val($(this).attr('placeholder'));
                    $(this).addClass('placeholder');
                }
            });
        });

        // Clean up any placeholders if the form gets submitted
        $('[placeholder]').parents('form').submit(function() {
            $(this).find('[placeholder]').each(function() {
                if ($(this).val() == $(this).attr('placeholder') && $(this).hasClass('placeholder')) {
                    $(this).val('');
                }
            });
        });

        // Clean up any placeholders if the page is refreshed
        window.onbeforeunload = function() {
            $('[placeholder]').each(function() {
                if ($(this).val() == $(this).attr('placeholder') && $(this).hasClass('placeholder')) {
                    $(this).val('');
                }
            });
        };
    }
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *