f7c9ae0f29544af740c09eb9f17e6a1a8b1db7f3
2 * HTML5 placeholder emulation for jQuery plugin
4 * This will automatically use the HTML5 placeholder attribute if supported, or emulate this behavior if not.
6 * @author Trevor Parscal <tparscal@wikimedia.org>, 2012
7 * @author Krinkle <krinklemail@gmail.com>, 2012
13 $.fn
.placeholder = function ( text
) {
15 return this.each( function () {
16 var placeholder
, $input
;
18 if ( arguments
.length
) {
19 this.setAttribute( 'placeholder', text
);
22 // If the HTML5 placeholder attribute is supported, use it
23 if ( this.placeholder
&& 'placeholder' in document
.createElement( this.tagName
) ) {
27 placeholder
= arguments
.length
? text
: this.getAttribute( 'placeholder' );
30 // Show initially, if empty
31 if ( this.value
=== '' || this.value
=== placeholder
) {
32 $input
.addClass( 'placeholder' ).val( placeholder
);
36 // Show on blur if empty
38 if ( this.value
=== '' ) {
39 this.value
= placeholder
;
40 $input
.addClass( 'placeholder' );
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
55 // IE wants getData( 'text' ) but Firefox wants getData( 'text/plain' )
56 // Firefox fails gracefully with an empty string, IE barfs with an error
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' );
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.
72 $input
.removeClass( 'placeholder' );
76 // Blank on submit -- prevents submitting with unintended value
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' ) ) {
85 .removeClass( 'placeholder' );