The dark mode is being saved via local storage, but it’s not being applied to all the site’s pages automatically. How can I make sure that when I choose dark mode, it is applied to all pages of the website automatically? How do I apply what I’ve saved in localstorage?
let trilho = document.getElementById('trilho');
let body = document.querySelector('body');
// Check local storage for the user's theme preference
const theme = window.localStorage.getItem("theme");
// Set the initial theme based on localStorage
if (theme === "dark") {
body.classList.add("dark");
trilho.classList.add("dark"); // Ensure the button reflects dark mode
} else {
trilho.classList.remove("dark"); // Ensure the button reflects light mode
}
// Add event listener to toggle dark mode
trilho.addEventListener('click', () => {
trilho.classList.toggle('dark');
body.classList.toggle('dark');
// Update localStorage with the current theme
if (body.classList.contains("dark")) {
window.localStorage.setItem("theme", "dark");
trilho.classList.add("dark"); // Dark mode button
} else {
window.localStorage.setItem("theme", "light");
trilho.classList.remove("dark"); // Light mode button
}
});