I try to use css var for changing dynamically an html page .
Here I have an exemple where I try to implement a dark mode switch.
const toggleDarkModeBtn = document.getElementById('toggle-dark-mode');
toggleDarkModeBtn.addEventListener('click', () => {
document.body.classList.toggle('dark');
if (document.body.classList.contains('dark')) {
toggleDarkModeBtn.textContent = 'Disable Dark Mode';
} else {
toggleDarkModeBtn.textContent = 'Enable Dark Mode';
}
});
:root {
--bg-color: #862e2e;
--text-color: #ffffff;
}
.dark :root {
--bg-color: #2d3748;
--text-color: #e2e8f0;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
<header>
<h1>Dark Mode Attempt</h1>
<button id="toggle-dark-mode">Enable Dark Mode</button>
</header>
<main>
<p>Click the button to toggle between modes.</p>
</main>
It add and remove the class dark on the root element but the page is not toggling the style.
Do you know what is the issue and how to use css var for changing style dynamically?