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],textarea[title]")
        .each( showPlaceholder ) // initialize each control on page load
        .blur( showPlaceholder )
        .focus( hidePlaceholder );
 
    $("form").submit( function() {
    	$( "input[type=text][title],textarea[title]", this ).each( hidePlaceholder );
    } );
 
    function showPlaceholder() {
    	var $control = $(this);
        var placeholderText = $control.attr("title");
        if ( $control.val() === "" || $control.val() === placeholderText ) {
        	$control.addClass("placeholder");
            $control.val(placeholderText);
        }
    };
 
    function hidePlaceholder() {
    	var $control = $(this);
        if ( $control.val() === $control.attr("title") ) {
        	$control.removeClass("placeholder");
        	$control.val("");
        }
    }
 
} );

Comments

 
 
  1. [...] This post was mentioned on Twitter by jarón barends. jarón barends said: Handig: Zet placeholder tekst in lege inputvelden mbv piepkleine jQuery plugin: http://bit.ly/aguEjY [...]

 
 

Leave a Reply

(will not be published)
(optional)

What My Clients Say

Travis has worked on several projects for us and we have an ongoing relationship which we value. He has excellent technical skills and communication skills. He is highly effective in taking a project from concept to completion. In addition, he is able to communicate with business professionals effectively.

—Clarence Johnson
FSI Holding Corp.