Dark mode website theme switcher with CSS and JavaScript using localStorage instead of cookies
A dark mode CSS/JS theme switcher to help reduce eyestrain in different lighting conditions, such as changing colors to light text on a dark background at night.
Try it by clicking on Lights in the navigation.
Your setting preference is saved with web browsers’ localStorage instead of cookies to help avoid needing “Accept Cookies” notes.
Here’s how to add it to your website:
-
Put data-theme="light" in your <html> tag:
<html data-theme="light" lang="en">
-
Set theme colors as variables in your linked stylesheet.css:
<link rel="stylesheet" href="/css/hypertexthero.css" type="text/css" />
Sample CSS code:
html[data-theme='light'] { --bg: rgba(221,221,221,1); --color-link: #1976d2; --color-text: #111; --code-bg:#fafafa; --code-text: #111; } html[data-theme='dark'] { --bg: rgba(51,51,51,1); --color-link: #81d4fa; --color-text: #eee; --code-bg:#252525; --code-text: #fafafa; } body { background-color: var(--bg); color: var(--color-text); } a { color: var(--color-link); } code { background-color: var(--code-bg); color: var(--code-text); }
- Add a toggle link to the HTML (see the ☼ & ☾ icons above):
<a id="switch" title="Toggle website lights.">☼ & ☾</a>
-
Link to the following theme switcher JavaScript code before the closing
</body>
tag of the page
<script src="/js/lights.js"></script> </body>
The JavaScript code:
// localStorage to remember light/dark theme preference // Based on code by Phina Kersly linked in lights.js // Keywords: mdn localstorage let theme = localStorage.getItem('data-theme'); const lightswitch = document.getElementById("switch"); const changeThemeToDark = () =>{ document.documentElement.setAttribute ("data-theme", "dark") localStorage.setItem("data-theme", "dark") console.log("Dark theme set") } const changeThemeToLight = () =>{ document.documentElement.setAttribute ("data-theme", "light") localStorage.setItem("data-theme", 'light') console.log("Light theme set") } if (theme === 'dark'){ changeThemeToDark() } lightswitch.addEventListener('click', ()=> { let theme = localStorage.getItem('data-theme'); if (theme ==='dark'){ changeThemeToLight() } else { changeThemeToDark() } });
See it working by clicking the ☼ & ☾ icons above.
Try refreshing the page after switching to light or dark mode to see that the browser remembers your setting by using localStorage, without needing cookies.
· ˖ ✦ . ˳
Possibly Related:
- Good user interface design
- Bad Button Names
- Good Old Reddit
- Introducing Food News
- The user experience of Lego interface panels
˳ · ˖
Prior entry: ♫ Echolocation
Next entry: GTA and Noita Updates