Reputation:
I'm trying to set up some simple theming with JS by changing a few css variables on :root by both a button click (theme should change immediately on click) and on page load (theme should be set based on localStorage item value).
Here is I guess my "draft" javascript which seems to work for the most part, except oddly enough button clicks do nothing, yet on page load the click events are run (each one in sequence!). I feel like I'm close but I'm obviously doing something wrong.
const root = document.documentElement.style,
button1 = document.getElementById("defaultBtn"),
button2 = document.getElementById("darkBtn"),
button3 = document.getElementById("lightBtn");
function setProperties(bg_color,fg_color,link_color,name) {
root.setProperty("--bg",bg_color);
root.setProperty("--fg",fg_color);
root.setProperty("--link-color",link_color);
console.log("Theme set to " + name);
}
function loadTheme() {
let theme = localStorage.getItem("theme");
switch (theme) {
case "dark":
setProperties("0%","59%","80%","dark");
break;
case "light":
setProperties("100%","0%","100%","light");
break;
case "default":
setProperties("90%","29%","90%","default");
break;
default:
console.log("Theme has not been set.");
}
}
function setTheme(name) {
localStorage.setItem("theme", name);
loadTheme();
}
window.addEventListener("DOMContentLoaded",loadTheme);
button1.addEventListener("click", setTheme("default"));
button2.addEventListener("click", setTheme("dark"));
button3.addEventListener("click", setTheme("light"));
Upvotes: 1
Views: 366
Reputation: 8938
Here is your problem. You are calling the function instead of passing it to the event listener which means the function runs instantly, instead of when the button is clicked.
button1.addEventListener("click", setTheme("default"));
The solution is to wrap the code in something called a Closure. Try this:
function setTheme(name) {
return function() {
localStorage.setItem("theme", name);
loadTheme(name);
}
}
Here's an example:
function onClick(msg) {
return function() {
console.log(msg)
}
}
const button = document.getElementById('btn')
button.addEventListener('click', onClick('Hello'))
<button id="btn">Press Me</button>
Upvotes: 1