views:

85

answers:

3

Hi,

I'm wondering what the best way is to set a global variable with Jquery / Javascript that can be used and updated by multiple functions.

I've a fairly over complex site that uses sliders(http://www.nwph.info/nwph/nwpho/) , I want to add a dynamic breadcrumb and thought that restructuring the code so that the various functions can read from one shared global variable would be much better than continuously passing the current clicked object name around.

Cheers Paul

+3  A: 

Normally you define global variables by just omitting var:

globalVar = "This is global!";

And as long as no local variable with the same name is defined, gobalVar will always refer to this one (even if a local variable with the same name exists, you can refer to the global one with window.globalVar).

Felix Kling
Cool cheers felix
Paul
+2  A: 

If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu under jQuery, and I place everything there.

The reason I use quotes when I talk about javascript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a javascript object and place all my functions and variables as properties of this object.

Also, for convenience, I usually sub-space the plugin namespace with an i namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.

This is how it works:

// An object to define utility functions and global variables on:
$.miniMenu = new Object(); 
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();

Now I can just do $.miniMenu.i.globalVar = 3 or $.miniMenu.i.parseSomeStuff = function(...) {...} whenever I need to save something globally, and I still keep it out of the global namespace.

Tomas Lycken
Thanks for that Tomas, In the site I mentioned above Felix approach works fine, but i have another site I'm also working on that uses several plugins and your approach would be ideal if i can get it to work.Cheers for your help.
Paul
+1  A: 

Here is a basic example of a global variable that the rest of your functions can access. Here is a live example for you: http://jsfiddle.net/fxCE9/

var myVariable = 'Hello';
alert('value: ' + myVariable);
myFunction1();
alert('value: ' + myVariable);
myFunction2();
alert('value: ' + myVariable);


function myFunction1() {
    myVariable = 'Hello 1';
}

function myFunction2() {
    myVariable = 'Hello 2';
}

If you are doing this within a jquery ready() function then make sure your variable is inside the ready() function alongwith your other functions.

Paul Dragoonis