for some reason it counts each click two times. Despite the fact that I’ve clicked for two times the console has 1, 2, 3, 4 logged. That’s not good because I want to use modulus of this count as a trigger for switching dark theme on and off.
The second question is that the global variable themeChangeClicksCount which is declared at the beginning of the script, is not updated even if I ad ad return at the end of themeChangeClicksCounter function. Like this (I’ve clicked the toggle and it still says 0):
here is my codepen showing some simple js to count up
edit: i think the reason your global counter is not showing as incremented is because you are logging it too early. (you log it before any clicks happen right?)
I can’t see anything useful right now in the pen. The images are broken, and I’m not sure what to click on to test.
I think you should take a look at my last comment…
Not sure why you would use a number increment for a theme switcher?
I would expect it to be either a boolean or a string value. Like isDarkMode = true or theme = 'dark'.
It is tempting to go with the boolean because it is easy to switch the value but the string value can be easier to reason about. Boolean logic can get confusing surprisingly quickly even for simple things.
If you want to log the variable being changed by an event handler, put the log inside the handler.
Example
const toggle = document.getElementById('toggle')
let isDarkMode = false;
toggle.addEventListener("change", function () {
isDarkMode = !isDarkMode;
console.log(isDarkMode)
});
@lasjorg I’ve figured it out, - it works but only for one cycle. With the click on the toggle switches to the dark theme, the next click one brings white back, and after that it stops responding
let theme = "light";
toggle.addEventListener("change", function () {
theme = theme === "light" ? applyDarkTheme() : applyLightTheme();
});