(bug 27944) Search placeholder was inserted even when the search box was already...
[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 * @author Krinkle <krinklemail@gmail.com>
8 * @version 0.2.0
9 * @license GPL v2
10 */
11 ( function( $ ) {
12
13 $.fn.placeholder = function() {
14
15 return this.each( function() {
16
17 // If the HTML5 placeholder attribute is supported, use it
18 if ( this.placeholder && 'placeholder' in document.createElement( this.tagName ) ) {
19 return;
20 }
21
22 var placeholder = this.getAttribute( 'placeholder' );
23 var $input = $(this);
24
25 // Show initially, if empty
26 if ( this.value === '' || this.value === placeholder ) {
27 $input.addClass( 'placeholder' ).val( placeholder );
28 }
29
30 $input
31 // Show on blur if empty
32 .blur( function() {
33 if ( this.value === '' ) {
34 this.value = placeholder;
35 $input.addClass( 'placeholder' );
36 }
37 } )
38
39 // Hide on focus
40 // Also listen for other events in case $input was
41 // already focused when the events were bound
42 .bind( 'focus drop keydown paste', function( e ) {
43 if ( $input.hasClass( 'placeholder' ) ) {
44 // Support for drag&drop in Firefox
45 if ( e.type == 'drop' && e.originalEvent.dataTransfer ) {
46 this.value = e.originalEvent.dataTransfer.getData( 'text/plain' );
47 } else {
48 this.value = '';
49 }
50 $input.removeClass( 'placeholder' );
51 }
52 } );
53
54 // Blank on submit -- prevents submitting with unintended value
55 if ( this.form ) {
56 $( this.form ).submit( function() {
57 // $input.trigger( 'focus' ); would be problematic
58 // because it actually focuses $input, leading
59 // to nasty behavior in mobile browsers
60 if ( $input.hasClass( 'placeholder' ) ) {
61 $input
62 .val( '' )
63 .removeClass( 'placeholder' );
64 }
65 });
66 }
67
68 });
69 };
70 } )( jQuery );