Applying whitespace conventions in core JS files.
[lhc/web/wiklou.git] / resources / jquery / jquery.placeholder.js
1 /**
2 * HTML5 placeholder emulation for jQuery plugin
3 *
4 * This will automatically use the HTML5 placeholder attribute if supported, or emulate this behavior if not.
5 *
6 * @author Trevor Parscal <tparscal@wikimedia.org>
7 * @author Krinkle <krinklemail@gmail.com>
8 * @version 0.2.0
9 * @license GPL v2
10 */
11 ( function( $ ) {
12
13 $.fn.placeholder = function() {
14
15 return this.each( function() {
16
17 // If the HTML5 placeholder attribute is supported, use it
18 if ( this.placeholder && 'placeholder' in document.createElement( this.tagName ) ) {
19 return;
20 }
21
22 var placeholder = this.getAttribute( 'placeholder' );
23 var $input = $(this);
24
25 // Show initially, if empty
26 if ( this.value === '' || this.value === placeholder ) {
27 $input.addClass( 'placeholder' ).val( placeholder );
28 }
29
30 $input
31 // Show on blur if empty
32 .blur( function() {
33 if ( this.value === '' ) {
34 this.value = placeholder;
35 $input.addClass( 'placeholder' );
36 }
37 } )
38
39 // Hide on focus
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
48 // dropped text.
49
50 // IE wants getData( 'text' ) but Firefox wants getData( 'text/plain' )
51 // Firefox fails gracefully with an empty string, IE barfs with an error
52 try {
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' );
58 }
59
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.
63 e.preventDefault();
64 } else {
65 this.value = '';
66 }
67 $input.removeClass( 'placeholder' );
68 }
69 } );
70
71 // Blank on submit -- prevents submitting with unintended value
72 if ( this.form ) {
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' ) ) {
78 $input
79 .val( '' )
80 .removeClass( 'placeholder' );
81 }
82 });
83 }
84
85 });
86 };
87 } )( jQuery );