Skip to content

Instantly share code, notes, and snippets.

@imcodetolive
Last active December 18, 2015 19:29
Show Gist options
  • Save imcodetolive/5833230 to your computer and use it in GitHub Desktop.
Save imcodetolive/5833230 to your computer and use it in GitHub Desktop.
/**
* Placeholder
* @author Diego Oliveira <[email protected]>
*/
;(function(){
var _private = {},
methods = {};
_private = {
onblur : function(force){
if (this.input.tagName.toLowerCase() === "input" && /(radio|checkbox|hidden)/gi.test(this.input.type)) return;
if (!this.value || force) {
$(this.input)
.val(this.input.getAttribute("placeholder"))
.addClass(this.klass);
};
},
onfocus : function(){
if (this.input.tagName.toLowerCase() === "input" && /(radio|checkbox|hidden)/gi.test(this.input.type)) return;
if (this.value === this.input.getAttribute("placeholder")) {
$(this.input)
.val("")
.removeClass(this.klass);
};
},
settings : {
klass : "placeholder",
selector : "input[placeholder], textarea[placeholder]"
}
};
methods = {
init : function(options){
$.extend(_private.settings, options);
$("body")
.on({
"blur.placeholder" : function(){
_private.onblur.call({
input : this,
klass : _private.settings.klass,
value : $.trim(this.value)
});
},
"focus.placeholder" : function(){
_private.onfocus.call({
input : this,
klass : _private.settings.klass,
value : $.trim(this.value)
});
}
}, _private.settings.selector)
.on("submit.placeholder", "form", function(){
var $placeholders = $(this).find(_private.settings.selector);
$placeholders.length && $placeholders.each(function(){
_private.onfocus.call({
input : this,
klass : _private.settings.klass,
value : $.trim(this.value)
});
});
});
methods.update.call( $(_private.settings.selector) );
},
add : function(fields){
$(fields).each(function(){
_private.onblur.call({
input : this,
klass : _private.settings.klass,
value : $.trim(this.value)
});
});
},
update : function(fields){
$(fields ? fields : _private.settings.selector).each(function(){
_private.onblur.call({
input : this,
klass : _private.settings.klass,
value : $.trim(this.value)
}, true);
});
}
};
$.placeholder = (function(support){
if (support) {
return function(){
return this;
};
} else {
return function(method){
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} if (typeof method === "object" || !method) {
return methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jQuery.placeholder");
};
};
};
})( !!("placeholder" in document.createElement("input")) );
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment