Improved on r74282 and r74333 in response to CR comments.
[lhc/web/wiklou.git] / resources / jquery / jquery.placeholder.js
1 /**
2 * HTML5 placeholder emulation for jQuery plugin
3 *
4 * This will automatically use the HTML5 placeholder attribute if supported, or emulate this behavior if not.
5 *
6 * @author Trevor Parscal <tparscal@wikimedia.org>
7 * @version 0.1.0
8 * @license GPL v2
9 */
10
11 jQuery.fn.placeholder = function( text ) {
12 // If the HTML5 placeholder attribute is supported, use it
13 if ( 'placeholder' in document.createElement( 'input' ) ) {
14 jQuery(this).attr( 'placeholder', text );
15 }
16 // Otherwise, use a combination of blur and focus event handlers and a placeholder class
17 else {
18 jQuery(this).each( function() {
19 var $input = jQuery(this);
20 $input
21 // Show on blur if empty
22 .bind( 'blur', function() {
23 if ( $input.val().length == 0 ) {
24 $input
25 .val( text )
26 .addClass( 'placeholder' );
27 }
28 } )
29 // Hide on focus
30 .bind( 'focus', function() {
31 if ( $input.hasClass( 'placeholder' ) ) {
32 $input
33 .val( '' )
34 .removeClass( 'placeholder' );
35 }
36 } )
37 // Blank on submit -- prevents submitting with unintended value
38 .parents( 'form' )
39 .bind( 'submit', function() {
40 $input.trigger( 'focus' );
41 } );
42 // Show initially, if empty
43 if ( $input.val() == '' ) {
44 $input.trigger( 'blur' );
45 }
46 } );
47 }
48 };