Skip to content

Instantly share code, notes, and snippets.

@lifo101
Last active October 7, 2015 13:08
Show Gist options
  • Save lifo101/3169494 to your computer and use it in GitHub Desktop.
Save lifo101/3169494 to your computer and use it in GitHub Desktop.
jquery plugin that adds HTML5 "placeholder" support for browsers that do not natively support it
// add HTML5 'placeholder' support to selected inputs if not natively supported.
// @example:
// $(':text[placeholder]').placeholder();
// @css:
// input.placeholder { color: #aaa; } /* since IE doesn't properly support :not() */
//
(function($){
if (document.createElement('input').placeholder !== undefined) {
$.fn.placeholder = $.noop;
} else {
var handlers = {};
$.fn.placeholder = function(name){
name = name || 'placeholder';
var onBlur = function(){
var me = $(this);
if (me.val() == '') {
me.val( me.attr(name) ).addClass(name);
}
};
var onFocus = function(){
var me = $(this);
if (me.val() == me.attr(name)) {
me.val('');
}
me.select().removeClass(name);
};
this.on({
'blur.placeholder': onBlur,
'focus.placeholder': onFocus
}).each(function(){
onBlur.apply(this, []);
});
// we must intercept form submits and remove the placeholder value
// or the value will be submitted with the form to the server.
if (!handlers[name]) {
// only install 1 handler per placeholder name
handlers[name] = true;
$(document).on('submit.placeholder-' + name, 'form', function(e){
if (!e.isDefaultPrevented() && !e.originalEvent.defaultPrevented) {
$(this).find(':input[' + name + ']').each(function(){
onRemove.apply(this, []);
});
}
});
}
return this;
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment