jquery.placeholder: Fixup for a8145d6fa2
[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>, 2012
7 * @author Krinkle <krinklemail@gmail.com>, 2012
8 * @version 0.2.0
9 * @license GPL v2
10 */
11 ( function ( $ ) {
12
13 $.fn.placeholder = function ( text ) {
14
15 return this.each( function () {
16 var placeholder, $input;
17
18 if ( arguments.length ) {
19 this.setAttribute( 'placeholder', text );
20 }
21
22 // If the HTML5 placeholder attribute is supported, use it
23 if ( this.placeholder && 'placeholder' in document.createElement( this.tagName ) ) {
24 return;
25 }
26
27 placeholder = arguments.length ? text : this.getAttribute( 'placeholder' );
28 $input = $(this);
29
30 // Show initially, if empty
31 if ( this.value === '' || this.value === placeholder ) {
32 $input.addClass( 'placeholder' ).val( placeholder );
33 }
34
35 $input
36 // Show on blur if empty
37 .blur( function () {
38 if ( this.value === '' ) {
39 this.value = placeholder;
40 $input.addClass( 'placeholder' );
41 }
42 } )
43
44 // Hide on focus
45 // Also listen for other events in case $input was
46 // already focused when the events were bound
47 .on( 'focus drop keydown paste', function ( e ) {
48 if ( $input.hasClass( 'placeholder' ) ) {
49 if ( e.type === 'drop' && e.originalEvent.dataTransfer ) {
50 // Support for drag&drop. Instead of inserting the dropped
51 // text somewhere in the middle of the placeholder string,
52 // we want to set the contents of the search box to the
53 // dropped text.
54
55 // IE wants getData( 'text' ) but Firefox wants getData( 'text/plain' )
56 // Firefox fails gracefully with an empty string, IE barfs with an error
57 try {
58 // Try the Firefox way
59 this.value = e.originalEvent.dataTransfer.getData( 'text/plain' );
60 } catch ( exception ) {
61 // Got an exception, so use the IE way
62 this.value = e.originalEvent.dataTransfer.getData( 'text' );
63 }
64
65 // On Firefox, drop fires after the dropped text has been inserted,
66 // but on IE it fires before. If we don't prevent the default action,
67 // IE will insert the dropped text twice.
68 e.preventDefault();
69 } else {
70 this.value = '';
71 }
72 $input.removeClass( 'placeholder' );
73 }
74 } );
75
76 // Blank on submit -- prevents submitting with unintended value
77 if ( this.form ) {
78 $( this.form ).submit( function () {
79 // $input.trigger( 'focus' ); would be problematic
80 // because it actually focuses $input, leading
81 // to nasty behavior in mobile browsers
82 if ( $input.hasClass( 'placeholder' ) ) {
83 $input
84 .val( '' )
85 .removeClass( 'placeholder' );
86 }
87 });
88 }
89
90 });
91 };
92
93 }( jQuery ) );