Complete the code to enable dark mode using a class in Tailwind CSS.
<html class="[1]"> <body> <h1 class="text-black dark:text-white">Hello, world!</h1> </body> </html>
The dark class on the html element activates Tailwind's dark mode styles.
Complete the Tailwind config to enable class-based dark mode.
module.exports = {
darkMode: '[1]',
theme: {
extend: {},
},
plugins: [],
}Setting darkMode to "class" tells Tailwind to use a class to toggle dark mode.
Fix the error in the JavaScript code that toggles dark mode by adding or removing the correct class on the <html> element.
const html = document.documentElement;
function toggleDarkMode() {
if (html.classList.contains('[1]')) {
html.classList.remove('dark');
} else {
html.classList.add('dark');
}
}The class to check and toggle is dark, matching Tailwind's dark mode class.
Fill both blanks to create a button that toggles dark mode on click.
<button onclick="document.documentElement.classList.[1]('[2]')"> Toggle Dark Mode </button>
The toggle method adds the class if missing or removes it if present. The class to toggle is dark.
Fill all three blanks to create a dark mode toggle that saves the preference in localStorage and applies it on page load.
<script>
const html = document.documentElement;
const toggle = () => {
html.classList.[1]('dark');
if (html.classList.contains('dark')) {
localStorage.setItem('[2]', '[3]');
} else {
localStorage.removeItem('[2]');
}
};
if (localStorage.getItem('[2]') === '[3]') {
html.classList.add('dark');
}
</script>The toggle method switches the 'dark' class. The localStorage key is 'dark-mode' and the value saved is 'enabled' to remember the preference.