Reputation:
How can I use a variable outside of a click()
in jQuery
? I have the following code -
$(".area").not(".enemy").click(function(){
$(".area").removeClass("clicked");
$(this).toggleClass("clicked");
attackValue = $(this).text();
});
When I want to use attackValue outside of the click()
It will not be defined.
Upvotes: 0
Views: 49
Reputation: 72672
For starters: this is NOT how you should declare a variable in javascript:
attackValue = $(this).text();
This would clutter 'programs' variable space. You should 'always' declare a variable in javascript using the var
keyword.
When I want to use attackValue outside of the click() It will not be defined.
It depends on where and when you want to use it. Consider the following code:
var attackValue = 'some value';
function setValue() {
attackvalue = 'some other value';
}
console.log(attackvalue); // this would output some value, because the function hasn;t run yet
setValue();
However if you would do:
var attackValue = 'some value';
function setValue() {
attackValue = 'some other value';
}
setValue();
console.log(attackValue); // this would output some other value, because the function did already run
Note that the above code should run in a closure. Or it would still clutter the variable space (even when using the var
) keyword. So it would look more like:
(function() { // yay closure, now all variables defined in here will stay in here
var attackValue = 'some value';
function setValue() {
attackValue = 'some other value';
}
setValue();
console.log(attackValue); // this would output some other value, because the function did already run
})();
Upvotes: 0
Reputation: 179
In order to keep attackValue defined outside of the scope of the function, you will need to declare it outside of your click event.
var attackValue;
$(".area").not(".enemy").click(function(){ ... });
Now you should be able to reference it outside.
Upvotes: 1