Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. jQuery Utilities > Testing Callback Functions with jQuery.isFunction

4.8. Testing Callback Functions with jQuery.isFunction

4.8.1. Problem

You have written a plugin and need to test whether one of the settings is a valid callback function.

4.8.2. Solution

(function($) {
    $.fn.myPlugin = function(settings) {
        return this.each(function() {
            settings = $.extend({ onShow: null }, settings);
            $(this).show();
            if ( $.isFunction( settings.onShow ) ) {
                settings.onShow.call(this);
            }
        });
    };
    $(document).ready(function() {
        $('div').myPlugin({
            onShow: function() {
                alert('My callback!');
            }
        });
    });
})(jQuery);

4.8.3. Discussion

While the JavaScript language provides the typeof operator, inconsistent results and edge cases across web browsers need to be taken into account. jQuery provides the .isFunction() method to ease the developer’s job. Worth pointing out is that since version 1.3, this method works for user-defined functions and returns inconsistent results with built-in language functions such as this:

jQuery.isFunction( document.getElementById );

which returns false in versions of Internet Explorer.