16

I have a JavaScript function to generate a variable. That function is activated by an onclick button event.

After that variable is generated, I need to use it as a global variable so that other JavaScript processes can use that variable.

How do I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eric Sim
  • 267
  • 1
  • 4
  • 8

2 Answers2

13

You should be able to add the variable's value to a property of the global window object:

window.yourVarName = yourVarName;

Then the other functions will be able to access yourVarName simply by referencing yourVarname directly. There will be no need to use window.yourVarName.

However keep in mind that in general, global variables are evil.

Community
  • 1
  • 1
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
3

Declare the variable outside the scope of the function:

var foo = null;

function myClickEvent() {
    foo = someStuffThatGetsValue;
}

Better yet, use a single global variable as the namespace ("MyApp") for your application, and store the value inside that:

var MyApp = {
    foo: null
};

function myClickEvent() {
    MyApp.foo = someStuffThatGetsValue;
}

The function itself could even be included in there.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
roryf
  • 29,592
  • 16
  • 81
  • 103