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:
The output is the following:
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
Tweet
6 comments:
The jQuery example will throw a ReferenceError if the function is not defined. It should be altered to test window.calculateSum as well.
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');
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
:) yes that's a good observation. I will get it changed this weekend and add a comma there!
Thanks Anonymous (what's your name?)
To test if jQuery has a fuctnion, use:
var hasCss = 'css' in $.fn;
Or
var hasCss = $.isFunction($.fn.css);
Although my previous comment suggests that the "g" stands for "Grammar nazi", my name is actually "Gregg". ;)
Post a Comment