Created
November 4, 2011 16:41
-
-
Save zrod/1339796 to your computer and use it in GitHub Desktop.
Placeholder fallback (HMTL 5)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Small workaround to support the 'placeholder' attribute found on HTML5's input elements. | |
* This version requires jquery 1.6+ | |
*/ | |
var myScript = ( function( $ ) { | |
function placeHolderFallback() { | |
var forms = $( 'form' ); | |
if ( forms.length > 0 ) { | |
forms.each( function( fk, fv ) { | |
var frm = $( fv ); | |
forms.find( '[placeholder]' ).each( function( k, v ) { | |
var el = $( v ), | |
elName = el.attr( 'name' ), | |
placeholderText = el.attr( 'placeholder' ), | |
isPassword = ( el.attr( 'type' ) == 'password' ), | |
hasValue = ( el.val() != '' ), | |
pwdEl; | |
if ( !hasValue ) { | |
el.val( placeholderText ); | |
if ( isPassword ) { | |
/* | |
* Placing the temporary element BEFORE the original one, in order to avoid messing | |
* with any other possible element used to handle messages or things of such nature. | |
* This may not work for all cases, but for ST we can use it safely. | |
*/ | |
el.hide() | |
.before( $( '<input type="text" value="' + placeholderText + '" id="cp_' + elName + '" class="' + el.attr( 'class' ) + '" />' ) ); | |
pwdEl = el.prev( '#cp_' + elName ); | |
pwdEl.show(); | |
pwdEl.bind( 'focus', function() { | |
if ( pwdEl.val() == placeholderText ) pwdEl.val( '' ); | |
}).bind( 'blur', function() { | |
if ( pwdEl.val() == '' ) pwdEl.val( placeholderText ); | |
}).bind( 'keydown', function() { | |
el.val( pwdEl.val() ).show().focus(); | |
pwdEl.hide(); | |
}); | |
} | |
el.bind( 'focus', function() { | |
if ( el.val() == placeholderText ) el.val(''); | |
}).bind( 'blur', function() { | |
if ( el.val() == '' ) { | |
if ( isPassword ) { | |
el.hide(); | |
pwdEl.show(); | |
} | |
el.val(placeholderText); | |
} | |
}); | |
} | |
}); | |
frm.submit(function() { | |
var elsWithPlaceholder = $( this ).find( '[placeholder]' ); | |
elsWithPlaceholder.each( function( ek, ev ) { | |
var ep = $( ev ); | |
if ( ep.val() == ep.attr( 'placeholder' ) ) { | |
ep.val( '' ); | |
} | |
}); | |
}) | |
}); | |
} | |
} | |
return { | |
init: function() { | |
// 'placeholder' fallback | |
if ( !( 'placeholder' in document.createElement( 'input' ) ) ) placeHolderFallback(); | |
} | |
}; | |
}) ( jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment