Reputation: 10696
Ho can I access and change the value of var
from outside the function?
var ArrowFlag = "1";
$('input, textarea, select').focusin( function() {
var ArrowFlag = "0";
//console.log(ArrowFlag) will = 0
});
$(document).bind('keyup', function() {
// When input:focus console.log(ArrowFlag) will = 1
});
When you have input:focus
event, var ArrowFlag
should have a value of 0
.
But, when you have keyUp
event after input:focus
var ArrowFlag value will be 1
. Why? Look like my var ArrowFlag
never had it's value changed.
Upvotes: 2
Views: 90
Reputation: 35793
You have defined two seperate variables called ArrowFlag
, if you want them to be the same variable remove the var from the one inside the focusin callback:
var ArrowFlag = "1";
$('input, textarea, select').focusin( function() {
ArrowFlag = "0";
//console.log(ArrowFlag) will = 0
});
$(document).bind('keyup', function() {
// after focusin ArrowFlag will now be 0
});
Example - http://jsfiddle.net/yyLPE
Upvotes: 1
Reputation: 7847
var
declares a variable in the current context, the top context being the DOM window.
Drop the var
in the function to avoid redeclaring a variable of same name in a different context.
Upvotes: 1
Reputation: 41757
In javascript variables are scoped to functions, you're declaring another ArrowFlag
inside the focusin
anonymous function that hides the outer ArrowFlag
. You do not need to declare ArrowFlag
again (by using var
), try the following:
var ArrowFlag = "1";
$('input, textarea, select').focusin( function() {
ArrowFlag = "0";
});
Upvotes: 1
Reputation: 16953
This is all about variable scope.
Remove the "var" from var ArrowFlag = "0"
, and take a read of http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/ or one of the many other articles about it - you'll be glad you did.
Upvotes: 3