Skip to content

Instantly share code, notes, and snippets.

@iamntz-gists
Created June 24, 2012 10:23
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 iamntz-gists/2982739 to your computer and use it in GitHub Desktop.
Save iamntz-gists/2982739 to your computer and use it in GitHub Desktop.
placeholder.js
(function( $, document ){
var enablePlaceholders = {
init: function( el ){
var $t = this, $ = jQuery;
$t.el = $(el).data( 'hasplaceholder', true );
$t.placeholder = $t.el.attr('placeholder');
$t.addPlaceholder( $t.el );
} // init
,clearValue: function( e ){
if( $(e).val() === $(e).data('placeholder') ) {
$(e).val('');
}
}//clearValue
,addPlaceholder: function(){
var $t = this;
$t.maybeShowPlaceholder();
$t.el.bind('blur.ntz_placeholder', $.proxy( $t.maybeShowPlaceholder, $t ) );
$t.el.bind('focus.ntz_placeholder', $.proxy( $t.maybeHidePlaceholder, $t ) );
} //addPlaceholder
,maybeShowPlaceholder: function(){
var $t = this;
if( $.trim( $t.el.val() ) !== '' ){ return; }
$t.el
.addClass('placeholder')
.val( $t.placeholder );
}//maybeShowPlaceholder
,maybeHidePlaceholder: function(){
var $t = this;
if( $t.el.hasClass('placeholder') &&
$t.el.val() == $t.placeholder ){
$t.el.val('')
}
}//maybeHidePlaceholder
};
$.fn.enablePlaceholders = function() {
var fakeInput = document.createElement("input"),
nativePlaceholder = ("placeholder" in fakeInput);
if (!nativePlaceholder) {
$('input[placeholder], textarea[placeholder]').filter(function(){
return !$(this).data('hasplaceholder')
}).each(function(){
var obj = Object.create( enablePlaceholders );
obj.init( this );
});
return this;
}
};
})( jQuery, document );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment