Created
June 24, 2012 10:23
-
-
Save iamntz-gists/2982739 to your computer and use it in GitHub Desktop.
placeholder.js
This file contains hidden or 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
(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