Simulating HTML5's placeholder attribute with jQuery

I recently discussed the placeholder attribute in HTML5. Today, I needed exactly such a behavior for a site I'm working on, so I knocked together a reusable, unobtrusive solution with jQuery.

Simply include this code (and jQuery, of course) on your page, and assign the placeholder text as the title attribute of the control. Example:

<input type="text" name="keywords" title="Search" />

The script also assigns the class placeholder to the control when the placeholder text is present, so you can style it differently if you like (for example, you may wish to gray out the text).

The code:

/**
 * Unobtrusively set up placeholder behaviors on all text inputs for which
 * the title attribute has been set. The title text will be used as the
 * placeholder text.
 * @author Travis Miller
 * @link http://www.electrumdigital.com/
 */
$( function() {
 
    $("input[type=text][title]")
        .each( function() {
            showPlaceholder( $(this) ); // initialize each control on page load
        } )
        .blur( function() {
            showPlaceholder( $(this) );
        } )
        .focus( function() {
            var $input = $(this);
            if ( $input.val() === $input.attr("title") ) {
                $input.removeClass("placeholder");
                $input.val("");
            }
        } );
 
    function showPlaceholder( $input ) {
        var placeholderText = $input.attr("title");
        if ( $input.val() === "" || $input.val() === placeholderText ) {
            $input.addClass("placeholder");
            $input.val(placeholderText);
        }
    };
 
} );

Comments

No comments yet.

Leave a Reply

(will not be published)
(optional)

What My Clients Say

Travis Miller's professionalism and experience is an invaluable asset to Airplane Corporation. His technical development skills are on par with the best in the industry. He completes projects on time and on budget, and is truly a pleasure to work with.

—Christian Childs
Airplane Corporation