Skip to content

Instantly share code, notes, and snippets.

@kristofferh
Created March 30, 2011 15:51
Show Gist options
  • Save kristofferh/894652 to your computer and use it in GitHub Desktop.
Save kristofferh/894652 to your computer and use it in GitHub Desktop.
Fallback for placeholder attribute
/**
* Quick/dirty polyfill for placeholder attribute
* Requirements: jQuery
* Usage:
* var placeIt = Placeholder.init('input#search');
*/
var Placeholder = (function() {
// private methods
var isSupported = function () {
return 'placeholder' in document.createElement('input');
};
return {
init: function (target, options) {
this.target = $(target);
this.form = this.target.parent('form');
this.options = $.extend({
focusClass: 'focus', // CSS class to set on target on focus
force: false, // force the input field to use fallback solution? Useful for testing
placeholderClass: 'placeholder' // CSS class for default (placeholder) styling
}, options || {});
// check if we need to fallback from placeholder attribute
if (!isSupported() || this.options.force === true) {
// if so call fallback method
this.fallback();
}
},
fallback: function () {
var self = this; // scope alias
// read placeholder attribute, if it exists set the value of the input
var placeholder = this.target.attr('placeholder');
if (placeholder) {
this.target.val(placeholder);
/**
* events
*/
this.target.bind('focus', function (e) {
self.setFocus($(this), placeholder);
});
this.target.bind('blur', function (e) {
self.setBlur($(this), placeholder);
});
this.form.bind('submit', function (e) {
var val = $.trim(self.target.val());
if (val === placeholder) {
self.target.val('');
}
});
}
},
// do things on focus
setFocus: function (el, placeholder) {
el.addClass(this.options.focusClass);
if (el.val() === placeholder) {
el.removeClass(this.options.placeholderClass);
el.val('');
}
},
// do stuff on blur
setBlur: function (el, placeholder) {
var val = el.val();
el.removeClass(this.options.focusClass);
if (val === '') {
el.addClass(this.options.placeholderClass);
el.val(placeholder);
}
}
};
})();
@dandean
Copy link

dandean commented Mar 31, 2011

It seems like that should exist here and not somewhere else. Otherwise, you're breaking the "placeholder" functionality up over disconnected bits of code, and if someone wants to use this, they have to implement both pieces instead of this one discreet piece.

@kristofferh
Copy link
Author

How dare you question my approach? No, I know, you are right so I added that functionality. I use these gists as a repository of half-baked ideas and/or snippets of in-progress work, not so much as production ready code. Maybe I should keep them private until they are fully featured, but I figured someone might find it useful. Also... I'm boring myself. Naptime!

@dandean
Copy link

dandean commented Apr 1, 2011

NO! Don't make them private! I love seeing what you're up to!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment