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 // Check whether supplied argument is a string
15 var textIsValid = ( typeof text === 'string' );
17 return this.each( function () {
18 var placeholder, $input;
21 // If the HTML5 placeholder attribute is supported, use it
22 if ( this.placeholder && 'placeholder' in document.createElement( this.tagName ) ) {
24 this.setAttribute( 'placeholder', text );
29 placeholder = textIsValid ? text : this.getAttribute( 'placeholder' );
32 // Show initially, if empty
33 if ( this.value === '' || this.value === placeholder ) {
34 $input.addClass( 'placeholder' ).val( placeholder );
38 // Show on blur if empty
40 if ( this.value === '' ) {
41 this.value = placeholder;
42 $input.addClass( 'placeholder' );
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
57 // IE wants getData( 'text' ) but Firefox wants getData( 'text/plain' )
58 // Firefox fails gracefully with an empty string, IE barfs with an error
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' );
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.
74 $input.removeClass( 'placeholder' );
78 // Blank on submit -- prevents submitting with unintended value
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' ) ) {
87 .removeClass( 'placeholder' );