Bird
Raised Fist0
Tailwindmarkup~5 mins

Dark mode toggle with JavaScript in Tailwind

Choose your learning style10 modes available
Introduction

Dark mode helps reduce eye strain in low light. A toggle lets users switch between light and dark themes easily.

You want your website to be easier to read at night.
You want to give users control over the website's look.
You want to save device battery on OLED screens.
You want to follow modern design trends.
You want to improve accessibility for sensitive eyes.
Syntax
Tailwind
<!-- HTML button -->
<button id="darkModeToggle">Toggle Dark Mode</button>

<!-- JavaScript -->
<script>
  const toggle = document.getElementById('darkModeToggle');
  toggle.addEventListener('click', () => {
    document.documentElement.classList.toggle('dark');
  });
</script>

The dark class on html triggers Tailwind's dark styles.

Use document.documentElement to add the class to the root element.

Examples
Basic toggle button that switches dark mode on and off.
Tailwind
<button id="darkModeToggle">Toggle Dark Mode</button>

<script>
  const toggle = document.getElementById('darkModeToggle');
  toggle.addEventListener('click', () => {
    document.documentElement.classList.toggle('dark');
  });
</script>
Improved toggle with accessibility using ARIA attributes.
Tailwind
<button id="darkModeToggle" aria-pressed="false" aria-label="Toggle dark mode">Toggle Dark Mode</button>

<script>
  const toggle = document.getElementById('darkModeToggle');
  toggle.addEventListener('click', () => {
    const isDark = document.documentElement.classList.toggle('dark');
    toggle.setAttribute('aria-pressed', isDark.toString());
  });
</script>
Sample Program

This page uses Tailwind CSS with a button to switch between light and dark modes. The background and text colors change smoothly. The button updates its ARIA state for accessibility.

Tailwind
<!DOCTYPE html>
<html lang="en" class="transition-colors duration-500">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Dark Mode Toggle</title>
  <script>
    tailwind.config = {
      darkMode: 'class',
    }
  </script>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 min-h-screen flex flex-col items-center justify-center">
  <button id="darkModeToggle" aria-pressed="false" aria-label="Toggle dark mode" class="px-6 py-3 bg-gray-200 dark:bg-gray-700 rounded-md focus:outline-none focus:ring-4 focus:ring-blue-500">
    Toggle Dark Mode
  </button>
  <p class="mt-6 text-lg">
    This text changes color based on the theme.
  </p>

  <script>
    const toggle = document.getElementById('darkModeToggle');
    toggle.addEventListener('click', () => {
      const isDark = document.documentElement.classList.toggle('dark');
      toggle.setAttribute('aria-pressed', isDark.toString());
    });
  </script>
</body>
</html>
OutputSuccess
Important Notes

Tailwind CSS must be configured to use class strategy for dark mode.

Adding smooth transitions improves user experience.

Always update ARIA attributes for accessibility when toggling states.

Summary

Dark mode toggle switches the dark class on the root html element.

Tailwind CSS uses this class to apply dark styles automatically.

Use JavaScript event listeners to handle user clicks on the toggle button.

Practice

(1/5)
1. What does adding the dark class to the html element do in Tailwind CSS?
easy
A. It disables all CSS styles on the page.
B. It enables dark mode styles throughout the website.
C. It changes the font size to larger values.
D. It hides all images on the page.

Solution

  1. Step 1: Understand Tailwind dark mode mechanism

    Tailwind applies dark mode styles when the dark class is present on the html element.
  2. Step 2: Effect of the dark class

    Adding dark triggers alternate color schemes and styles designed for dark backgrounds.
  3. Final Answer:

    It enables dark mode styles throughout the website. -> Option B
  4. Quick Check:

    dark class = enables dark mode [OK]
Hint: Remember: dark class on html toggles dark mode styles [OK]
Common Mistakes:
  • Thinking dark class disables styles
  • Confusing dark class with font size changes
  • Assuming dark class hides images
2. Which JavaScript code correctly toggles the dark mode class on the html element when a button is clicked?
easy
A. document.documentElement.classList.toggle('dark');
B. document.body.classList.add('dark');
C. document.getElementById('dark').classList.remove('dark');
D. document.querySelector('html').style.dark = true;

Solution

  1. Step 1: Identify the root element for dark mode

    Dark mode toggles the dark class on the html element, accessible as document.documentElement.
  2. Step 2: Use correct method to toggle class

    The classList.toggle('dark') method adds or removes the class on each click.
  3. Final Answer:

    document.documentElement.classList.toggle('dark'); -> Option A
  4. Quick Check:

    Toggle dark class on html element = document.documentElement.classList.toggle('dark'); [OK]
Hint: Use document.documentElement.classList.toggle('dark') to toggle dark mode [OK]
Common Mistakes:
  • Using document.body instead of document.documentElement
  • Using add or remove instead of toggle
  • Trying to set style.dark property which doesn't exist
3. What will be the visible background color of this page after clicking the toggle button once?
<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>
medium
A. Gray background (#1a202c)
B. No background color
C. Black background
D. White background

Solution

  1. Step 1: Initial state has dark class on html

    The page starts with dark class, so background is gray (#1a202c) from dark:bg-gray-900.
  2. Step 2: Clicking toggle removes dark class

    Toggle removes dark class, so bg-white applies, making background white.
  3. Final Answer:

    White background -> Option D
  4. Quick Check:

    Toggle removes dark class, background = white [OK]
Hint: Toggle flips dark class, switching background colors [OK]
Common Mistakes:
  • Assuming background stays gray after toggle
  • Confusing initial class presence
  • Ignoring that toggle removes dark class
4. This JavaScript code is meant to toggle dark mode but does not work. What is the error?
const btn = document.getElementById('toggle');
btn.onclick = function() {
  document.querySelector('html').classList.add('dark');
  document.querySelector('html').classList.remove('dark');
};
medium
A. The class name should be 'dark-mode', not 'dark'.
B. The selector 'html' is incorrect; should be 'body'.
C. It adds and removes 'dark' class immediately, so no visible change.
D. The event listener should be 'addEventListener', not 'onclick'.

Solution

  1. Step 1: Analyze the toggle logic

    The code adds then immediately removes the dark class on the same element in one function call.
  2. Step 2: Effect on the page

    Because add and remove happen instantly, the class never stays applied, so no dark mode effect is visible.
  3. Final Answer:

    It adds and removes 'dark' class immediately, so no visible change. -> Option C
  4. Quick Check:

    Immediate add and remove cancels out [OK]
Hint: Toggle class once; don't add and remove immediately [OK]
Common Mistakes:
  • Thinking 'onclick' is invalid
  • Using wrong selector for dark mode
  • Confusing class name with 'dark-mode'
5. You want to save the user's dark mode preference so it stays after page reload. Which JavaScript approach correctly implements this with Tailwind CSS?
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?
hard
A. if(localStorage.getItem('theme') === 'dark') { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); }
B. document.documentElement.classList.toggle(localStorage.getItem('theme'));
C. localStorage.setItem('theme', document.documentElement.classList.contains('dark'));
D. document.body.classList.add(localStorage.getItem('theme'));

Solution

  1. Step 1: Retrieve saved theme from localStorage

    Use localStorage.getItem('theme') to get saved preference.
  2. Step 2: Apply or remove 'dark' class based on preference

    If preference is 'dark', add dark class to html, else remove it.
  3. Final Answer:

    if(localStorage.getItem('theme') === 'dark') { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } -> Option A
  4. Quick Check:

    Check saved theme and add/remove class accordingly [OK]
Hint: Check localStorage theme and add/remove 'dark' class on html [OK]
Common Mistakes:
  • Using toggle with localStorage value directly
  • Saving boolean instead of string in localStorage
  • Adding class to body instead of html
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard