Performance: Dark mode toggle with JavaScript
This affects page interactivity and visual stability when toggling themes.
const toggleDarkMode = () => {
document.documentElement.classList.toggle('dark');
};
button.addEventListener('click', toggleDarkMode);const toggleDarkMode = () => {
document.body.style.backgroundColor = '#000';
document.body.style.color = '#fff';
};
button.addEventListener('click', toggleDarkMode);| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline style changes per property | Multiple style updates on body | Multiple reflows triggered | High paint cost due to many changes | [X] Bad |
| Toggle single CSS class on root | One class toggle on <html> | Single reflow triggered | Minimal paint cost | [OK] Good |
dark class to the html element do in Tailwind CSS?dark class is present on the html element.dark classdark triggers alternate color schemes and styles designed for dark backgrounds.html element when a button is clicked?dark class on the html element, accessible as document.documentElement.classList.toggle('dark') method adds or removes the class on each click.<html class="dark">
<body class="bg-white dark:bg-gray-900">
<button id="toggle">Toggle Dark Mode</button>
</body>
</html>
<script>
document.getElementById('toggle').addEventListener('click', () => {
document.documentElement.classList.toggle('dark');
});
</script>dark class on htmldark class, so background is gray (#1a202c) from dark:bg-gray-900.dark classdark class, so bg-white applies, making background white.const btn = document.getElementById('toggle');
btn.onclick = function() {
document.querySelector('html').classList.add('dark');
document.querySelector('html').classList.remove('dark');
};dark class on the same element in one function call.1. On toggle, add/remove 'dark' class on <html>. 2. Save preference in localStorage. 3. On page load, read preference and set 'dark' class accordingly. Which code snippet correctly sets dark mode on page load?
localStorage.getItem('theme') to get saved preference.dark class to html, else remove it.Pass the test and this pattern moves unknown