tailwind dark mode

How to toggle dark mode in tailwindcss and JavaScript?

To style, your website in dark mode, use Tailwind CSS because it is very simple to use.
It’s getting more and more usual to create a dark version of your website. Now the dark mode is a primary feature of many operating systems.

Tailwind has a dark class that enables you to layout your site differently when dark mode is set:

Include Tailwindcss

For simplicity we will go with the CDN link here, however, you can read more on the installation of Tailwind here.

<head>
  <script src="https://cdn.tailwindcss.com"></script>
</head>

If you want to activate dark mode manually rather than relying on the operating system preference then add darkMode: 'class', to the tailwind.config.js file.

module.exports = {

  darkMode: 'class',

}

Now add the class="dark" to the HTML tag.

<html class="dark" id="html-tag">
<body>

  <!-- web page body -->

</body>
</html>

Make sure to include the prefix in the dark class if you’ve defined one in your Tailwind configuration. To enable dark mode, for instance, you must use the tw-dark class if your prefix is tw-.

<html class="tw-dark" id="html-tag">

Whenever you use dark:classname it will reflect the changes accordingly.

<div class="bg-white dark:bg-black">

Toggle dark mode using JavaScript

It’s time to toggle the dark mode using JavaScript.  A typical method involves using some JavaScript that gets a preference from somewhere (like localStorage) and updates the DOM accordingly.

<button id="dark-mode-icon"  onclick="toggleMode()">Toggle Dark Mode </button>
let html = document.getElementById('html-tag');
let icon = document.getElementById('dark-mode-icon');

let toggleMode = () => {
     
    if (html.classList.contains('dark')) {
      html.classList.remove('dark');
      html.classList.add('light');
      
      // store the value in localStorage
      localStorage.theme = 'light';
      
    } else {
      html.classList.add('dark');
      html.classList.remove('light');
      localStorage.theme = 'dark';
    }

  }

  if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {

    html.classList.add('dark');
    html.classList.remove('light');
    localStorage.theme = 'dark';

    } else {
      html.classList.remove('dark');
      html.classList.add('light');
      localStorage.theme = 'light';
  }

You can also save your preference in a database on the server and render the class in an HTML tag. In this way, you can also toggle dark mode in Tailwindcss.

References

Tailwind Dark mode is explained on the official site. This tutorial is also written with the help of official documentation.

Add comment