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 ) {
14 var hasArg = arguments.length;
16 return this.each( function () {
17 var placeholder, $input;
20 this.setAttribute( 'placeholder', text );
23 // If the HTML5 placeholder attribute is supported, use it
24 if ( this.placeholder && 'placeholder' in document.createElement( this.tagName ) ) {
28 placeholder = hasArg ? text : this.getAttribute( 'placeholder' );
31 // Show initially, if empty
32 if ( this.value === '' || this.value === placeholder ) {
33 $input.addClass( 'placeholder' ).val( placeholder );
37 // Show on blur if empty
39 if ( this.value === '' ) {
40 this.value = placeholder;
41 $input.addClass( 'placeholder' );
46 // Also listen for other events in case $input was
47 // already focused when the events were bound
48 .on( 'focus drop keydown paste', function ( e ) {
49 if ( $input.hasClass( 'placeholder' ) ) {
50 if ( e.type === 'drop' && e.originalEvent.dataTransfer ) {
51 // Support for drag&drop. Instead of inserting the dropped
52 // text somewhere in the middle of the placeholder string,
53 // we want to set the contents of the search box to the
56 // IE wants getData( 'text' ) but Firefox wants getData( 'text/plain' )
57 // Firefox fails gracefully with an empty string, IE barfs with an error
59 // Try the Firefox way
60 this.value = e.originalEvent.dataTransfer.getData( 'text/plain' );
61 } catch ( exception ) {
62 // Got an exception, so use the IE way
63 this.value = e.originalEvent.dataTransfer.getData( 'text' );
66 // On Firefox, drop fires after the dropped text has been inserted,
67 // but on IE it fires before. If we don't prevent the default action,
68 // IE will insert the dropped text twice.
73 $input.removeClass( 'placeholder' );
77 // Blank on submit -- prevents submitting with unintended value
79 $( this.form ).submit( function () {
80 // $input.trigger( 'focus' ); would be problematic
81 // because it actually focuses $input, leading
82 // to nasty behavior in mobile browsers
83 if ( $input.hasClass( 'placeholder' ) ) {
86 .removeClass( 'placeholder' );