Search code examples
javascriptjqueryfunctioninstanceoftypeof

Check if a JavaScript function is a method for a jQuery element


How do you detect if a function is a method for a jQuery element?

For example, $.fn.fadeIn is a function:

      typeof $.fn.fadeIn === 'function' //true

However, I need a way to distinguish it from a regular non-jQuery method. The goal is to be able to pass a function as a parameter and then call the function correctly.

Below is an example using a function called doIt that takes a jQuery element and a function to be applied to the element.

Example HTML:

<h1>jQuery Function Test</h1>
<p class=t1>Highlight this line.</p>
<p class=t2>Hide this line.</p>

Example JavaScript:

function doIt(elem, func) {
   if (func === 'a jQuery function')  //possible?
      func.apply(elem);
   else
      func(elem);
   }

function highlight(elem) {
   elem.css('background-color', 'gold');
   }

doIt($('p.t1'), highlight);
doIt($('p.t2'), $.fn.fadeOut);

Line #2 of the JavaScript needs help.

Interactive version:

      http://jsfiddle.net/sxduwke9/


Solution

  • Here’s a solution that combines the string parameter idea, checking if the method exists on the object, and support for parameters...

    function doIt(elem, func, params) {
        if (typeof func === 'function')
            func.apply(elem, [elem].concat(params));
        else if (elem[func] && params instanceof Array)
            elem[func](params[0], params[1], params[2]);
        else if (elem[func])
            elem[func](params);
    }
    

    or on jsfiddle