John Cooper
John Cooper

Reputation: 7631

Variable value does not change why?

Here's the code:

var popupFirstName;
PopupFirstNameButton.addEventListener('click', function(){
    popupFirstName = 'SomeValue';
});

When I alert(popupFirstName) in some other function it says undefined. How can I get the value?

Upvotes: 2

Views: 3196

Answers (4)

Steve Hansell
Steve Hansell

Reputation: 17703

You're missing the third argument for the addEventListener function. For Firefox for example, you would need:

PopupFirstNameButton.addEventListener('click', function(){
    popupFirstName = 'SomeValue';
}, false);

https://developer.mozilla.org/en/DOM/element.addEventListener

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

popupFirstName has a scope local to where it is placed, which we don't know from what you've told us. But I imagine it is in a function, so the scope will be local to that function. The function you've defined inherits access to that variable; this is a convenience feature of the language.

If you'd like to make a single instance of the variable that has global scope, write window.popupFirstName.

Upvotes: 3

pixelbobby
pixelbobby

Reputation: 4440

make sure this variable is declared in the same block scope as the function calling it.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816292

In which browser are you testing? Firefox needs a third parameter for addEventListener and IE uses a completely different method (attachEvent).

You can try to assign the function to onclick:

PopupFirstNameButton.onclick = function(){
    popupFirstName = 'SomeValue';
};

If you want to learn more about advanced event handling and its cross browser issues, or about JavaScript and events in general, I suggest to read the good articles on quirksmode.org.

It goes without saying that the button has to be clicked before the variable is set and that the function where you call alert(popupFirstName) has to have access to the variable.

Upvotes: 1

Related Questions