James Peter Mitchell How I made this site's theme switcher Posts Posted June 24, 2025 Updated November 25, 2025 4 minutes
I just finished adding a theme switcher to my site. It's now available on the Extra page. This was fairly straight-forward, and I managed to complete it start-to-finish in an hour or two. For the sake of posterity, and to help anyone who might stumble 👢 onto this page, here's how I did it.
HTML
This is the html for the theme selector. I prefer to use custom tags instead of ids or classes. onclick is set to call the js function that will perform the switch. data-theme declares the theme assigned to the button.
<theme-switcher><theme-switcher-buttononclick="setTheme('alt0')"data-theme="alt0"> Coral Burst </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt1')"data-theme="alt1"> Sunset Pink </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt2')"data-theme="alt2"> Violet Bloom </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt3')"data-theme="alt3"> Lavender Light </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt4')"data-theme="alt4"> Sky Blue </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt5')"data-theme="alt5"> Ocean Breeze </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt6')"data-theme="alt6"> Mint Fresh </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt7')"data-theme="alt7"> Spring Green </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt8')"data-theme="alt8"> Lime Zest </theme-switcher-button><theme-switcher-buttononclick="setTheme('alt9')"data-theme="alt9"> Golden Honey </theme-switcher-button></theme-switcher>
html1157 charsclick to copy
CSS
Nothing particularily interesting here. All accents across the site use the --color-primary variable. I created a separate selector for all potential values of the data-theme attribute. The relevant detail is just that the theme color is being displayed prominantly on the button (through the :hover and .theme-active selector).
This is the important part. First, I get the inital value for the selected theme. I pull a previously selected theme from localStorage if it exists, otherwise I set a default.