Oscar Strangio
Oscar Strangio

Reputation: 149

JS - Running a jQuery function with a variable name

I need to run a function with a part dynamic variable in it's name.

The function to run:

$.element_gallery = function(state){}

The code that's calling it:

var name = "gallery";
window["$.element_"+name]('refresh');

This method seems to work with traditional Javascript functions but not with a jQuery function. Is there a way to run this without using eval() and without changing the function name?

Upvotes: 0

Views: 53

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

When you do window["$.foo"] it's looking for a property on the window object that's called $.foo. However, if you're using a jQuery function it's stored in the jQuery (or $) property of the window object, so the actual location of the function you want is window.$["foo"]. Change your code to:

var name = "gallery";
window.$["element_"+name]('refresh');

Or, since you can access global variables without specifying window., just:

var name = "gallery";
$[".element_"+name]('refresh');

Upvotes: 1

Andreas
Andreas

Reputation: 21881

Replace window with $

$["element_" + name]("refresh")

Upvotes: 2

Related Questions