Dark Mode Toggle using JS & Tailwind

This tutorial shows you how to create a dark mode toggle switch for your website using Tailwind CSS and JavaScript. Improve your user experience with a smooth theme transition that users can control easily.

Dark Mode Toggle

Why Dark Mode?

Dark mode helps reduce eye strain, saves battery on OLED screens, and gives a modern look to your interface. Providing users the choice enhances usability and accessibility.

HTML & Tailwind Setup

To begin, ensure that your HTML structure includes a root element like html or body where the dark class will be applied. Tailwind supports dark mode via the media or class strategy. We will use class strategy here for full control.

<html class="dark">
  <body class="bg-white text-black dark:bg-[#0f172a] dark:text-white">
    <!-- Your content here -->
  </body>
</html>
    

JavaScript Toggle Logic

Next, create a button that toggles the dark class on the root element. This lets you dynamically change themes with a single click. To retain user preference across sessions, save the theme state in localStorage.

const toggle = document.getElementById('darkToggle');
toggle.addEventListener('click', () => {
  document.documentElement.classList.toggle('dark');
  if (document.documentElement.classList.contains('dark')) {
    localStorage.setItem('theme', 'dark');
  } else {
    localStorage.setItem('theme', 'light');
  }
});

// Load saved theme
if (localStorage.getItem('theme') === 'dark') {
  document.documentElement.classList.add('dark');
}
    

Button Example

You can use a simple button or a fancy switch UI. Here's an example button implementation:

<button id="darkToggle" class="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700">
  Toggle Dark Mode
</button>
    

Tailwind Configuration

Ensure your tailwind.config.js is set to use the class strategy. This enables dark mode toggling using the dark class rather than relying on system settings.

module.exports = {
  darkMode: 'class',
  theme: {
    extend: {},
  },
  plugins: [],
}
    

Tips for Smooth Transitions

Add transition classes from Tailwind to enable smooth background and text color changes when toggling themes. Example:

<body class="transition-colors duration-300 bg-white text-black dark:bg-[#0f172a] dark:text-white">
  ...
</body>
    

Conclusion

With just a few lines of JavaScript and Tailwind configuration, you can implement a powerful dark mode toggle. Consider enhancing this with user interface elements like toggle switches, icons, or animations to make the experience even more engaging.