Created
November 8, 2011 15:42
-
-
Save alvincrespo/1348100 to your computer and use it in GitHub Desktop.
A polyfill for the placeholder attribute
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
var Utils = Utils || {}; | |
Utils = (function (window, $) { | |
var _c, _private, _public; | |
_private = { | |
/** | |
* @event | |
* @param e The event object. | |
*/ | |
'handleFocusIn': function (e) { | |
var $target = $(e.currentTarget); | |
if($target.val() === $target.attr('placeholder')) { | |
$target.val(''); | |
} | |
$target | |
.unbind('focusin') | |
.bind('focusout', _private.handleFocusOut); | |
}, | |
/** | |
* @event | |
* @param e The event object. | |
*/ | |
'handleFocusOut': function (e) { | |
var $target = $(e.currentTarget); | |
if($target.val() === '') { | |
$target.val($target.attr('placeholder')); | |
} | |
$target | |
.unbind('focusout') | |
.bind('focusin', _private.handleFocusIn); | |
} | |
}; | |
_public = { | |
/** | |
* @function | |
* @description | |
* A poly-fill for the placeholder attribute. | |
*/ | |
'supportsPlaceholderAttr': function (enableFallback) { | |
var placeHolderSupported = false; | |
//If enableFallback is either undefined or not a Boolean, set it to false | |
if((typeof enableFallback === 'undefined') || !(enableFallback instanceof Boolean)) { | |
enableFallback = false; | |
} | |
//if placeholder is supported, no reason to continue on | |
if ('placeholder' in document.createElement("input")) { | |
return placeHolderSupported = true; | |
} | |
if (!placeHolderSupported && !!enableFallback) { | |
var $inputEle; | |
$('input') | |
.each( function(index, ele) { | |
$inputEle = $(ele); | |
if($inputEle.attr('placeholder')) { | |
$inputEle | |
.val($inputEle.attr('placeholder')) | |
.bind('focusin', _private.handleFocusIn); | |
} | |
}); | |
} | |
} | |
}; | |
return _public; | |
}(window, jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment