cafe-toggle-theme v1.0.1
Toggle Theme
Overrides user's theme preference, saves it in the local storage and automatically syncs the image src
attributes to load the appropriate image.
In the browser, we can detect the user's theme preference using the CSS media query prefers-color-scheme
:
@media (prefers-color-scheme: dark) {
/* User prefers dark theme */
}
@media (prefers-color-scheme: light) {
/* User prefers light theme */
}
But, to let the user override the value and look at our site in dark mode —even when their OS is setup to use light themes—, we need to use some JS code.
Images
Instead of setting the src
attribute, set data-src
where you can use the {theme}
variable that will be replaced with the user's selected theme.
For instance, the following <img>
declaration:
<img data-src="assets/{theme}/logo.webp" alt="Website's logo" />
would be transformed into:
<img
src="assets/dark/logo.webp"
data-src="assets/{theme}/logo.webp"
alt="Website's logo"
/>
when the 'dark' theme is preferred, or:
<img
src="assets/light/logo.webp"
data-src="assets/{theme}/logo.webp"
alt="Website's logo"
/>
if the 'light' theme is preferred.
Transition
Right after the theme is toggled, the CSS is-animating
class is added to the <body>
during one second.
Use this class to produce animations on theme changes:
body[data-theme='dark'] {
--text-color: #eaeaea;
--bg-color: #ffffff;
}
body[data-theme='light'] {
--text-color: #1f1f1f;
--bg-color: #ffffff;
}
body.is-animating {
transition: background 0.5s ease-out, color 0.5s ease-out;
}