jQuery: Check if Function Exists before Calling

This post shows how to check if a function exists, before calling it. We will use both JavaScript as well as jQuery (JavaScript library) to do so.

Using JavaScript

In order to check if a function exists using plain JavaScript, use the following code:

check function exists

The output is the following:

image

Using jQuery

jQuery contains the jQuery.isFunction() which finds out if the parameter passed to it is a function.

<script type="text/javascript">
function
calculateSum() {
}

// using jQuery
if ($.isFunction(window.calculateSum))
calculateSum();
else
document.writeln('calculateSum does not exist');
</script>

Since calculateSum() exists, the method gets called.

Check plenty of similar jQuery/JavaScript tips here

6 comments:

  1. The jQuery example will throw a ReferenceError if the function is not defined. It should be altered to test window.calculateSum as well.

    ReplyDelete
  2. JFSIII - Thanks for the pointer. It's fixed now. By the way for all inbuilt functions, the following can also be used

    if ('data' in $)
    alert('$.data exists');
    else
    alert('$.data does not exists');

    ReplyDelete
  3. Thanks for the post...that's a good tip. I wasn't aware of jQuery's "isFunction" method.

    I know this is off-topic but I do have a little suggestion regarding your site's tagline: "What's cooking developers?" I think you mean, "What's cooking, developers?" Otherwise, the lack of the comma in the tagline suggests that developers are actually being cooked by some unknown entity. ;)

    Not a major issue at all but I thought I'd let you know.
    - g

    ReplyDelete
  4. :) yes that's a good observation. I will get it changed this weekend and add a comma there!

    Thanks Anonymous (what's your name?)

    ReplyDelete
  5. To test if jQuery has a fuctnion, use:

    var hasCss = 'css' in $.fn;
    Or
    var hasCss = $.isFunction($.fn.css);

    ReplyDelete
  6. Although my previous comment suggests that the "g" stands for "Grammar nazi", my name is actually "Gregg". ;)

    ReplyDelete