<input class="check" type="checkbox">
<div class="themed">Theme</div>
:root[color-theme='light'] {
--background: #fff;
--boxColor: #000;
}
:root[color-theme='dark'] {
--background: #000;
--boxColor: #fff;
}
html {
background: var(--background);
}
.themed {
display: block;
width: 10em;
height: 10em;
background: var(--boxColor);
color: var(--background);
}
const $checkbox = document.querySelector('.check');
const isUserColorTheme = localStorage.getItem('color-theme');
const isOsColorTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
const getUserTheme = () => isUserColorTheme ? isUserColorTheme : isOsColorTheme;
window.onload = function() {
if (getUserTheme === 'dark') {
localStorage.setItem('color-theme', 'dark');
document.documentElement.setAttribute('color-theme', 'dark');
$checkbox.setAttribute('checked', true)
} else {
localStorage.setItem('color-theme', 'light');
document.documentElement.setAttribute('color-theme', 'light');
}
}
$checkbox.addEventListener('click', e=> {
if (e.target.checked) {
localStorage.setItem('color-theme', 'light');
document.documentElement.setAttribute('color-theme', 'dark');
} else {
localStorage.setItem('color-theme', 'light');
document.documentElement.setAttribute('color-theme', 'light');
}
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.