Check function existence before calling in Javascript/JQuery

September 28th, 2012 by laeeq | No comments

Sometimes we need to check of function existence in Javascript/JQuery before calling it. This is very simple, just use Javascript window object to check for function. if you are using JQuery, use jQuery.isFunction to check function existence. Here in this I have explained how to test function exists before calling it.

Javascript codes to check if function exists

  1. // javascript function
  2. function myFunction() {
  3. }
  4. // javascript code to check if function exist
  5. if(window.myFunction) {
  6. document.writeln(‘myFunction exists’);
  7. }
  8. else {
  9. document.writeln(‘myFunction does not exist’);
  10. }

jQuery codes to check if function exists

  1. if( jQuery.isFunction(jQuery.fn.myFunction) ){
  2. jQuery(document).myFunction();
  3. }

 

You can subscribe to PHPZAG.COM posts by Email

 

 

 

  1. No comments yet.
  1. No trackbacks yet.