views:

121

answers:

2

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.

+3  A: 

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");
Sinan Taifour
+1 good tip, too much global var advice floating around on SO!!
redsquare
+2  A: 

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.

inkedmn