Skip to content

Instantly share code, notes, and snippets.

@hatched
Created October 1, 2012 20:13
Show Gist options
  • Select an option

  • Save hatched/3814136 to your computer and use it in GitHub Desktop.

Select an option

Save hatched/3814136 to your computer and use it in GitHub Desktop.
Add placeholder support to old browsers
YUI.add('placeholder', function(Y) {
var VALUE = 'value',
PLACEHOLDER = 'placeholder',
elements = {},
events = [];
/*
* The sync method allows you to add additional inputs to the page and then resync the placeholders
*/
function sync() {
fetchElements();
render();
}
/*
* Checks to see if this browser has placeholder
* support before continuing
*/
function initializer() {
if (!placeholderSupport()) {
sync();
}
}
/*
* Detaches all of the events attached to input fields from this widget
*
* @method destructor
* @private
* @since 1.0.0
*/
function destructor() {
Y.Array.each(this.events, function(e) {
e.detach();
});
}
/*
* Retrieves all of the input elements on the page
*/
function fetchElements() {
elements = Y.all('input[type=text]');
}
/*
* Loops through all of the elements and sets
* the placeholders and events on text inputs
*
* @method render
* @public
* @since 1.0.0
*/
function render() {
elements.each(function(i) {
if (i.get(VALUE) == "") {
setPlaceholder(i);
setEvents(i);
}
}, this);
}
/*
* Sets the placeholder value as the value of the input
*
* @method setPlaceholder
* @param element {Node} an input node
* @public
* @since 1.0.0
*/
function setPlaceholder(element) {
element.set(VALUE, element.getAttribute(PLACEHOLDER));
}
/*
* Adds the event listeners to the input
*
* @method setEvents
* @param element {Node} an input node
* @public
* @since 1.0.0
*/
function setEvents(element) {
events.push(element.on('focus', function(e) {
var currentTarget = e.currentTarget;
if (currentTarget.get(VALUE) == currentTarget.getAttribute(PLACEHOLDER)) {
currentTarget.set(VALUE, "");
}
}));
events.push(element.on('blur', function(e) {
if (e.currentTarget.get(VALUE) == "") {
setPlaceholder(e.currentTarget);
}
}, this));
}
/*
* Check if the browser supports placeholders, if it does then do nothing.
*
* @method placeholderSupport
* @public
* @return {Bool} returns true if supported, false if otherwise
* @since 1.0.0
*/
function placeholderSupport() {
var node = document.createElement('input');
if (PLACEHOLDER in node) {
return true;
}
return false;
}
Y.after('domready', initializer);
Y.namespace('Placeholder').sync = sync;
}, "1.0.0", {requires: ['event-base', 'node']});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment