console
const btn = document.querySelector(".btn-toggle");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const currentTheme = localStorage.getItem("theme");
if (currentTheme === "dark") {
document.body.classList.toggle('dark-theme');
} else if (currentTheme === 'light') {
document.body.classList.toggle('light-theme');
}
btn.addEventListener('click', function() {
if (prefersDarkScheme.matches) {
document.body.classList.toggle('light-theme');
var theme = document.body.classList.contains('light-theme') ? 'light' : 'dark';
} else {
document.body.classList.toggle('dark-theme');
var theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
}
localStorage.setItem('theme', theme)
})
<button class="btn-toggle">Toggle Dark-Mode</button>
<h1>Hey there! This is just a title</h1>
<p>I am just a boring text, existing here solely for the purpose of this demo</p>
body {
--text-color: #222;
--bkg-color: #fff;
}
body .dark-theme {
--text-color: #eee;
--bkg-color: #121212;
}
@media(prefers-color-scheme: dark) {
body {
--text-color: #eee;
--bkg-color: #121212;
}
body.light-theme {
--text-color: #222;
--bkg-color: #fff;
}
}
* {
font-family: Arial, Helvetica, sans-serif;
}
body {
background: var(--bkg-color);
}
h1,
p {
color: var(--text-color);
}