Let's say we have the following jQuery plugins
$.accordion();
$.button();
and in a script we have the following code:
var plg = "accordion";
$('selector').plg();
plg = 'button';
$('selector').plg();
The above example, ofcource doesn't work. But is there a way to do something similar, without the usage of eval() ?
Can I execute jQuery plugins from variable ?
Roko C. Buljan
209k41 gold badges335 silver badges347 bronze badges
asked Nov 3, 2012 at 10:04
KodeFor.Me
13.5k30 gold badges104 silver badges174 bronze badges
2 Answers 2
Sure you can!
var plg = "accordion";
$('selector')[plg]();
answered Nov 3, 2012 at 10:07
Roko C. Buljan
209k41 gold badges335 silver badges347 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
KodeFor.Me
That was the correct answer :) It works fine ! I will check it as correct in 3 minutes :) Thanks a lot
If what you want is to make an alias for that function you can just assign it, no need for a string or eval:
var plg = $.accordion;
$('selector').plg();
answered Nov 3, 2012 at 10:07
elclanrs
94.2k21 gold badges137 silver badges171 bronze badges
3 Comments
KodeFor.Me
This is not wat I need. I want to run my plugin from a variable name. In example var plg = "pluginname"; $('selector').plg(); Is it posible to make the same thing like var plg = $."pluginname"; ?
elclanrs
Mmmm, it wasn't very clear by your question, but roXon's answer seems to be what you're looking for.
KodeFor.Me
Thanks for your response anyway :)
lang-js