Last Updated: January 03, 2017
·
589
· iantearle

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');
});

1 Response
Add your 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 ·