0

I have a list of dependant methods in jquery. I would like to test dynamicaly if they exists. I tired this simple way:

console.log(jQuery.isFunction($.fn.popover));

which returned true. But when I put method name into variable I received a false.

var func = '$.fn.popover';
console.log(jQuery.isFunction(window[func]));

Does anybody know how can I test if method exists from variable. Thanks

Bjørson Bjørson
  • 1,583
  • 1
  • 17
  • 31
  • First thing to check: what does `$.fn.popover === window['$.fn.popover']` return, just out of curiosity? – msanford Dec 13 '17 at 20:54
  • as I expected return false but when I try `var func = 'jQuery'; console.log(jQuery.isFunction(window[func]));` I receive true. Even with `var func = '$'`; – Bjørson Bjørson Dec 13 '17 at 20:58
  • You can try this way: var func = $.fn.popover; – Hanif Dec 13 '17 at 21:01
  • That ^ won't work because you assign _the function_, which you need to know already exists, to the variable. Presumably OP wants to check for feature support using the string name of the function. – msanford Dec 13 '17 at 21:05
  • Thanks it worked as in linked thread. Problem with that thread was that it is not easy to find it. So I recommend this question to leave it here to others find also answer. – Bjørson Bjørson Dec 13 '17 at 21:06
  • @msanford I am not assigning function itself, I am assigning only function name as text with quotas. – Bjørson Bjørson Dec 13 '17 at 21:08
  • You can try if it work for you: var func = $.fn.popover; console.log(jQuery.isFunction(window.func)) – Hanif Dec 13 '17 at 21:09
  • @BjørsonÅlmer I know, that's what I was saying to Hanif: you want to do something fundamentally different than his suggestion allows. That's why I hinted at testing equality beforehand. The linked question marked as duplicate will help :) – msanford Dec 13 '17 at 21:09
  • Ok, thanks for your clarification @msanford. Your contribute was helpfull :-) – Bjørson Bjørson Dec 13 '17 at 21:24
  • 1
    If `jQuery.noConflict()`is used then `window.$` will not be `jQuery`. Is heavily used in wordpess for example. Might be better to string replace `'$'` with `'jQuery'` – charlietfl Dec 13 '17 at 21:25

0 Answers0