Skip to main content

Theme control

Themes​

tsc script.ts

How It Works:​

CSS Variables: Global variables for background and text color (--background-color and --text-color) are defined in the root selector :root.
Themes: For each theme (dark, Halloween), when a class is activated on the <body> element, the values of these variables change, which automatically updates the styles of all elements using these variables.
Theme Management: In JavaScript, clicking on buttons changes the class on the <body> element, activating the corresponding theme and applying the styles through CSS variables.
With this approach, you don't need to add separate states for each element in the CSS—just use variables. This simplifies maintaining and extending styles for new themes.

// Find the theme toggle buttons
const defaultModeButton = document.getElementById(
"default-mode-toggle",
) as HTMLButtonElement;
const darkModeButton = document.getElementById(
"dark-mode-toggle",
) as HTMLButtonElement;
const halloweenModeButton = document.getElementById(
"halloween-mode-toggle",
) as HTMLButtonElement;

// Function to set the theme
function setTheme(theme: string): void {
// Remove all theme classes from the body
document.body.classList.remove("dark-mode", "halloween-mode");

// If a specific theme is selected, apply it and adjust button visibility
if (theme !== "default") {
document.body.classList.add(theme);
defaultModeButton.style.display = "block";
darkModeButton.style.display = "none";
halloweenModeButton.style.display = "none";
} else {
// If the default theme is selected, reset the button visibility
defaultModeButton.style.display = "none";
darkModeButton.style.display = "block";
halloweenModeButton.style.display = "block";
}
}

// Event listeners for the buttons
defaultModeButton.addEventListener("click", () => setTheme("default"));
darkModeButton.addEventListener("click", () => setTheme("dark-mode"));
halloweenModeButton.addEventListener("click", () => setTheme("halloween-mode"));
Big O