An updated most used jQuery function
This is an improved exists function in jQuery. It allows for the old method or all in one callback without the need for an if(). See example.
jQuery.fn.exists = function(fn) {
if(this.length>0) {
var f = arguments[0];
arguments[0] = function(e) {
f(e);
}
fn.apply( this, arguments );
return fn ? this.bind(name, fn) : this.trigger(name);
} else {
return this.length>0;
}
}
Example
$(EXISTING_ELEMENT).exists(function(e) {
$(EXISTING_ELEMENT).removeClass('hidden');
});
Written by Ian Tearle
Related protips
1 Response
I would remove the last else and just return false at the end or return false inside the else instead of this.length>0 as it will only be reached if the condition is false, else it'll get inside the if and use its return instead.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#