Created
February 6, 2014 12:16
-
-
Save ryanand26/8843054 to your computer and use it in GitHub Desktop.
Shim for placeholder support (My version)
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
/*jslint bitwise: true, eqeqeq: true, passfail: false, nomen: false, plusplus: false, undef: true, evil: true */ | |
/*global window, document, $, jQuery, LBI, self, Modernizr, setTimeout, define, require */ | |
define("utils/placeholder-shim", function () { | |
var hasPlaceholder, | |
placeHolderClass = 'showing-placeholder'; | |
function testForPlaceholder (){ | |
var i = document.createElement('input'); | |
return 'placeholder' in i; | |
} | |
function bindEvents (target, select) { | |
var targetElements = target; | |
if (select) { | |
target | |
.on('focus', select, onFocus) | |
.on('blur', select, onBlur); | |
targetElements = target.find(select); | |
} | |
else { | |
target | |
.on('focus', onFocus) | |
.on('blur', onBlur); | |
} | |
targetElements.each(function (i, elem) { | |
onBlur.call(elem); | |
}); | |
} | |
/** | |
* When focused, test if the value of the form field matches the placeholder value. If it does remove this value. | |
*/ | |
function onFocus (event) { | |
var $element = $(this), | |
placeholderValue = $element.attr('placeholder'), | |
formValue = $element.val(); | |
if (formValue === placeholderValue) { | |
$element.val('').removeClass(placeHolderClass); | |
} | |
} | |
/** | |
* When blurred, test if the value of the form field is empty. If iso reset to the placeholder value. | |
*/ | |
function onBlur (event) { | |
var $element = $(this), | |
placeholderValue = $element.attr('placeholder'), | |
formValue = $element.val(); | |
if (formValue === '') { | |
$element | |
.val(placeholderValue) | |
.addClass(placeHolderClass); | |
} | |
} | |
function init (target, select) { | |
//test for placeholder if this is the first call | |
if (hasPlaceholder === undefined) { | |
hasPlaceholder = testForPlaceholder(); | |
} | |
if (hasPlaceholder === false) { | |
bindEvents(target, select); | |
} | |
return hasPlaceholder; | |
} | |
return { | |
init: init | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment