Adding a theme switcher to the website
March 12, 2025
A new year, a new website design. This year I went with a less modern, more brutalism inspired theme with sharp edges and thick borders.
However, to offset the doom and gloom of the theme, I added an accent colour (seen below) to anchor tags and buttons.
As a first (of hopefully many) little easter eggs for the site, I've added a theme swithing button in the navigation bar (or the footer if you're on mobile).
So here's how I added it using TailwindCSS and a few lines of JavaScript.
Tailwind Config
theme: {
extend: {
colors: {
accent: "var(--color-accent)",
},
},
},
app.css
/* Themes */
.theme-green {
--color-accent: theme("colors.green.500");
}
.theme-cyan {
--color-accent: theme("colors.cyan.500");
}
/* Add more here */
app.js
document.addEventListener("DOMContentLoaded", function () {
const themeButtons = document.getElementsByClassName("theme-button");
const themes = [
"theme-green",
"theme-cyan",
// Add more here
];
for (let i = 0; i < themeButtons.length; i++) {
themeButtons[i].addEventListener("click", function () {
const theme = themes[Math.floor(Math.random() * themes.length)];
document.documentElement.className = theme;
localStorage.setItem("theme", theme); // Persist the theme
});
}
// Load saved theme on page load
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
document.documentElement.className = savedTheme;
}
});
My favourite part of this fun trick is storing the theme in localStorage so the accent colour persists between visits for every user.
That's all for now! Thanks for stopping by 🧙♂️