user120944
user120944

Reputation:

Pass a var to external jQuery

How can I write

 var menu = $('.something');

and use it in an external .js file like so:

 $(menu).attr("class", "active");

I have also tried declaring the external js file after the inline code and it will not work.

Upvotes: 1

Views: 2001

Answers (2)

brettkelly
brettkelly

Reputation: 28225

As long as you define menu before you import the external js file that references it, I don't see why it wouldn't work. Like:

<script type="text/javascript">
    menu = $('.something');
</script>
<script type="text/javascript" src="/js/fileThatReferencesMenu.js"></script>

Give that a try.

Upvotes: 1

Sinan Taifour
Sinan Taifour

Reputation: 10805

Don't use the var keyword. This will render the variable global.

It is not a very good idea, though; It messes up your global namespace (and can thus create problems if you have multiple javascript files from different origins messing up the global namespace and overriding each other's variables).

A cleaner solution would be setting up a global object with a very unique name, and then adding properties to it. For example:

MyProject = {};
MyProject.menu = $(".something");

Then somewhere else:

$(MyProject.menu).attr("class", "active");

Upvotes: 6

Related Questions