I've recently had some trouble wrapping my head around the way javascript behaves when a function is called from an html tag (e.g.: onmouseleave()).
In the following example, bloonClick is called from a div's onclick():
function bloonClick() {
const bloon = document.getElementById("balloon");
let currSize = bloon.clientWidth;
colourShift(bloon, 1);
if (currSize <= 420) {
bloon.style.width = (currSize + 10) + "px";
bloon.style.height = (currSize + 10) + "px";
} else {
bloon.style.width = "200px";
bloon.style.height = "200px";
}
}
let colourCode = 0;
function colourShift(bloon, trigger) {
let colourArr = ["#42c742", "#3232d7", "#d73232"];
colourCode += trigger;
if (colourCode < 0) {
colourCode = 2;
} else if (colourCode > 2) {
colourCode = 0;
}
bloon.style.background = colourArr[colourCode];
}
As you can see, colourCode
is declared in the global scope and used inside colourShift()
. For some reason I don't quite understand this leads to what I consider static behaviour (at least from my C background, static has a whole other meaning related to objects in JS from what I've read), since the value of colourCode
is preserved in-between bloonClick()
calls.
That by itself is enough to make me confused, but the reason behind this question is that after a bit of testing I found out moving const bloon = document.getElementById("balloon");
to the global scope (which seemed interesting since the same getElementById()
is used in another function not present here) not only does not present the same static behaviour, it doesn't work at all.
Can someone please explain why these two things happen?
Thanks in advance :)