Created
August 15, 2012 13:08
-
-
Save dsheiko/3359967 to your computer and use it in GitHub Desktop.
Emulates H5Forms placeholders on legacy browsers
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
/* | |
* 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