I was wondering if you could review the following code I've written as a polyfill for the placeholder attribute in HTML5?
The object of the polyfill is to replicate the functionality of the placeholder attribute. In effect, the polyfill is supposed to do the following:
- Default text to be shown.
- On Focus: Erase the default text.
- On Focus Out: Put in default text if nothing has been entered
Dependancies:
jQuery
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));
enableFallback && run loop
. i used a short circuiting trickery to make sure you only bunch the focusin/out handlers in if the enableFallback flag is set \$\endgroup\$