How to emulate Emulate CSS media feature prefers-color-scheme using JavaScript or CSS, not in Chrome Developer Tools?
I tried color-scheme: light
and color-scheme: dark
but doesn't work as expected.
const changeColorSchemeButton = document.querySelector('.change-color-scheme');
const box = document.querySelector('.box');
changeColorSchemeButton.addEventListener('click', function() {
if (box.classList.contains('color-scheme-dark')) {
box.classList.remove('color-scheme-dark');
box.classList.add('color-scheme-light');
} else {
box.classList.add('color-scheme-dark');
box.classList.remove('color-scheme-light');
}
})
.box {
width: 200px;
height: 200px;
background: red;
color: blue;
}
.color-scheme-light {
color-scheme: light;
}
.color-scheme-dark {
color-scheme: dark;
}
@media (prefers-color-scheme: dark) {
.box {
background: grey;
color: white;
}
}
<div class="box">
test
</div>
<button class="change-color-scheme">Change Color Scheme</button>
As you can see, clicking the button will toggle color-scheme-dark
and color-scheme-light
classes, but the result is the same.
But it's working with Chrome Developers Tool Emulate CSS media feature prefers-color-scheme
feature to simulate dark and light modes truly.
How do I truly simulate dark and light modes using JavaScript and CSS?