icon in the footer of this page.
// This function is attached a button’s `onclick` event
function setTheme() {
if (document.documentElement.getAttribute("data-theme") === "dark") {
localStorage.setItem("theme", "light");
} else {
localStorage.setItem("theme", "dark");
}
document.documentElement.setAttribute("data-theme", localStorage.getItem("theme"));
}
If you noticed in the code above, in addition to attaching a new data-attribute to the root, we are also storing the user’s preference inside a localStorage
item—making it easy for the user to navigate through the rest of the site without losing the value the previously enabled.
Note: if you wanna be extra user friendly you could switch out
localStorage
forsessionStorage
so that their preference sticks around even if they close the page.