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