Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Created August 15, 2012 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsheiko/3359967 to your computer and use it in GitHub Desktop.
Save dsheiko/3359967 to your computer and use it in GitHub Desktop.
Emulates H5Forms placeholders on legacy browsers
/*
* Emulates H5Forms placeholders on legacy browsers
*
* <input placeholder="Search" />
*
* @author $Author: sheiko $
* @license MIT
* @copyright (c) Dmitry Sheiko http://www.dsheiko.com
*/
(function( window, undefined ){
var $ = window.jQuery,
document = window.document,
Browser = {
/*
* List of supported properties of input element
* Run through HTML5's new input attributes to see if the UA understands any.
* Implementation adopted from http://www.modernizr.com
* spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
supportedInputProps: (function() {
var inputElem = document.createElement('input'),
attrs = (function( props ) {
for ( var i = 0, attrs = [], len = props.length; i < len; i++ ) {
attrs[ props[i] ] = !!(props[i] in inputElem);
}
return attrs;
})('autocomplete autofocus list placeholder max min multiple pattern required step'
.split(' '));
return attrs;
}())
},
h5FormShim = (function() {
return {
init : function() {
var $inputs, that = this;
if ( !Browser.supportedInputProps[ "placeholder" ] ) {
$inputs = $( ":input[placeholder]" );
$inputs.each(function( inx, node ){
$( node ).attr( "placeholder" ) !== undefined
&& that.handleOnBlur.call( node );
})
$inputs
.on( "focus", this, this.handleOnFocus)
.on( "blur", this, this.handleOnBlur);
}
},
handleOnFocus : function() {
if ($( this ).val() === $( this ).attr( 'placeholder' )) {
$( this ).val( '' );
$( this ).removeClass( 'placeholder' );
}
},
handleOnBlur : function() {
if (!$( this ).val()) {
$( this ).val($( this ).attr( 'placeholder' ));
$( this ).addClass( 'placeholder' );
}
}
}
}());
$( document ).ready(function(){
h5FormShim.init();
});
}( window ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment