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