I need to change a global variable through a click event, but it seems (I suspect) that it won't change that variable value outside the event. i'm looking for making some calculations based on local variables from click events. When I declare it I get a message that local variables are not defined. It’s understandable because event hasn’t happened yet. Even after it does I can read updated values of local variables in browser console but global variable still remains undefined.
Here is some of the relevant code:
const tanqueSel = document.getElementById("tanqueSel"),
soldadoSel = document.getElementById("soldadoSel"),
guerreroSel = document.getElementById("guerreroSel"),
vikingoSel = document.getElementById("vikingoSel");
let Eleccion
tanqueSel.addEventListener("click", clickTanque)
function clickTanque() {
Eleccion = {
...tanque
};
alert("Has seleccionado " + Eleccion.nombre);
//I can access the new 'Eleccion' values here, but not outside
}
soldadoSel.addEventListener("click", clickSoldado)
function clickSoldado() {
Eleccion = {
...soldado
};
alert("Has seleccionado " + Eleccion.nombre);
}
guerreroSel.addEventListener("click", clickGuerrero)
function clickGuerrero() {
Eleccion = {
...guerrero
};
alert("Has seleccionado " + Eleccion.nombre);
}
vikingoSel.addEventListener("click", clickVikingo)
function clickVikingo() {
Eleccion = {
...vikingo
};
alert("Has seleccionado " + Eleccion.nombre);
}
let daño = (Eleccion.ataque - monstruo.defensa);
//According to the console this is where the problem is, since 'Eleccion' is undefined
It's a big antipattern to use global variables.
Also, the reason that you get undefined is because you're accessing that variable on the initial call stack of the application (that means that no click has happened yet, so yes, it is undefined).
I'm assuming that you are trying to calculate the 'damage' of an attack method.
When do you want to apply that damage? Shouldn't it be inside the click handler as well?
soldadoSel.addEventListener("click", clickSoldado)
function clickSoldado(){
// you can remove completely the global variable and use a generic function
attack(soldado);
}
//...same for every other click listener (you call attack method with the selection)
// and create a generic attack function
function attack(selected) {
alert("Has seleccionado " + selected.nombre);
let daño = selected.ataque - monstruo.defensa;
// here you have the damage, you can do what you want with it.
//...
}