Skip to content

Instantly share code, notes, and snippets.

@nfreear
Last active June 11, 2022 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfreear/3940b62ef375386de921b4eaa82ea804 to your computer and use it in GitHub Desktop.
Save nfreear/3940b62ef375386de921b4eaa82ea804 to your computer and use it in GitHub Desktop.
My-dark-mode / user theme switcher
<!doctype html> <title> Dark mode </title>
<meta name="color-scheme" content="dark light">
<style>
:root {
color-scheme: light dark; /* both supported */
}
* {
transition: all 250ms;
}
body {
background-color: #fefefe;
color: #333;
font: 1rem/1.6 sans-serif;
}
a {
color: blue;
text-decoration: underline;
}
/* @media (prefers-color-scheme: dark) {
body {
background-color: #333;
color: #fff;
}
a {
color: #adf; /* lightblue *-/
}
} */
[ data-my-user-theme = dark ] body {
background-color: #333;
color: #fff;
X-border: 2px solid red;
}
[ data-my-user-theme = dark ] a {
color: #adf; /* lightblue */
}
/* Toggler. */
.dark-mode-toggler button {
cursor: pointer;
font: inherit;
padding: .5rem 1.5rem;
}
.dark-mode-toggler [ aria-pressed = true ] {
background: pink;
}
</style>
<my-dark-mode>
<h1> Dark mode </h1>
<p> Hello world! </p>
<p>
<a href="#">I'm a link</a> |
<input value="I'm a text field">
<button>I'm a button</button>
</p>
<p class="dark-mode-toggler">
<button
data-theme="light" aria-pressed="false"
>Light
</button><button
data-theme="dark" aria-pressed="false"
>Dark
</button>
</p>
</my-dark-mode>
<script>
const { localStorage, matchMedia } = window;
const override = null;
const prefersDarkScheme = matchMedia('(prefers-color-scheme: dark)');
const prefersTheme = prefersDarkScheme.matches ? 'dark' : 'light';
const currentSetting = override || localStorage.getItem('my-user-theme') || prefersTheme;
const TOGGLER = document.querySelector('.dark-mode-toggler');
const BUTTONS = TOGGLER.querySelectorAll('button');
const CURRENT_BTN = TOGGLER.querySelector(`[ data-theme = ${currentSetting} ]`);
CURRENT_BTN.setAttribute('aria-pressed', 'true');
document.documentElement.setAttribute('data-my-user-theme', currentSetting);
TOGGLER.addEventListener('click', ev => {
ev.preventDefault();
// Reset.
BUTTONS.forEach(btn => btn.setAttribute('aria-pressed', 'false'));
const BTN = ev.target;
const THEME = ev.target.dataset.theme;
BTN.setAttribute('aria-pressed', 'true');
localStorage.setItem('my-user-theme', THEME);
document.documentElement.setAttribute('data-my-user-theme', THEME);
console.debug('DM click:', THEME, prefersDarkScheme, ev);
});
</script>
<pre>
NDF, 11-Jun-2022.
* https://css-tricks.com/a-complete-guide-to-dark-mode-on-the-web/#aa-using-custom-properties,
* https://tink.uk/about-leonie/
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment