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 () {
15 return this.each( function () {
16 var placeholder, $input;
18 // If the HTML5 placeholder attribute is supported, use it
19 if ( this.placeholder && 'placeholder' in document.createElement( this.tagName ) ) {
23 placeholder = this.getAttribute( 'placeholder' );
26 // Show initially, if empty
27 if ( this.value === '' || this.value === placeholder ) {
28 $input.addClass( 'placeholder' ).val( placeholder );
32 // Show on blur if empty
34 if ( this.value === '' ) {
35 this.value = placeholder;
36 $input.addClass( 'placeholder' );
41 // Also listen for other events in case $input was
42 // already focused when the events were bound
43 .on( 'focus drop keydown paste', function ( e ) {
44 if ( $input.hasClass( 'placeholder' ) ) {
45 if ( e.type === 'drop' && e.originalEvent.dataTransfer ) {
46 // Support for drag&drop. Instead of inserting the dropped
47 // text somewhere in the middle of the placeholder string,
48 // we want to set the contents of the search box to the
51 // IE wants getData( 'text' ) but Firefox wants getData( 'text/plain' )
52 // Firefox fails gracefully with an empty string, IE barfs with an error
54 // Try the Firefox way
55 this.value = e.originalEvent.dataTransfer.getData( 'text/plain' );
56 } catch ( exception ) {
57 // Got an exception, so use the IE way
58 this.value = e.originalEvent.dataTransfer.getData( 'text' );
61 // On Firefox, drop fires after the dropped text has been inserted,
62 // but on IE it fires before. If we don't prevent the default action,
63 // IE will insert the dropped text twice.
68 $input.removeClass( 'placeholder' );
72 // Blank on submit -- prevents submitting with unintended value
74 $( this.form ).submit( function () {
75 // $input.trigger( 'focus' ); would be problematic
76 // because it actually focuses $input, leading
77 // to nasty behavior in mobile browsers
78 if ( $input.hasClass( 'placeholder' ) ) {
81 .removeClass( 'placeholder' );