57ar7up
57ar7up

Reputation: 442

Check if jQuery method exists

Is it possible? No matter how, in Javascript or jQuery.

For example: $.isFunction($.isFunction());

Upd: But how to check method of a jQuery plugin? Sometimes it not ready at the moment of it call and generates error. Example: $.isFunction($().jqGrid.format)

Upvotes: 7

Views: 4641

Answers (2)

bobince
bobince

Reputation: 536379

To pass a function to another function, leave the () off:

$.isFunction($.isFunction);   // true!

When you write () you are calling the function, and using the result it returns. $.isFunction() with no argument returns false (because undefined isn't a function), so you are saying $.isFunction(false), which is, naturally, also false.

I wouldn't bother using isFunction merely to check for the existence of something, unless you suspect that someone might have assigned a non-function value to it for some reason. For pure existence-checking, use the in operator:

if ('isFunction' in $) { ...

Upvotes: 8

Mike Johnson
Mike Johnson

Reputation: 351

Yes,

jQuery.fn.exists = function(){return jQuery(this).length>0;}

if ($(selector).exists()) {
    // code........
}

Upvotes: 0

Related Questions