Switching Between Dark and Light Mode in Your Web App: A Step-by-Step Guide Using Tabler UI kit

Switching between dark and light mode has become a popular feature in modern web applications. It provides users with the flexibility to choose a theme that best suits their preferences, and it also helps reduce eye strain when working in low-light conditions. In this article, we’ll explore how to implement a dark and light mode toggle in a web application built with the Tabler, a free and open-source UI kit based on Bootstrap 5.

We’ll take a step-by-step approach to building this feature, and you’ll see how easy it is to customize and add this functionality to your own web applications.

Two Ways to Add Tabler Theme: Download or Use CDN Links

To use the Tabler in your project, you have two options. You can either download the necessary files from the Tabler GitHub repository (https://github.com/tabler/tabler) and include them in your project, or you can include the Tabler CDN links on the head of your HTML document.

The Tabler is built on top of Bootstrap 5, which means it includes all the necessary CSS and JavaScript files for Bootstrap. The file ‘tabler.min.css’ contains all the necessary styles for the theme and your project.

Using the Tabler CDN links is a convenient way to include the theme in your project. By including the following lines in the head of your HTML document, you can quickly add the necessary CSS files to your project:

<!-- Tabler project & Icons on Head-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest/tabler-icons.min.css">
<!-- Tabler on end of the body -->
<script src="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/js/tabler.min.js"></script>

These lines include the latest versions of the Tabler core CSS and the Tabler icons from the jsDelivr CDN. This method has the advantage of always serving the latest version of the theme, so you don’t have to worry about updating the files manually.

Switch between the light and dark theme

In order to switch between the light and dark themes in Tabler, you simply need to add the class theme-dark to the body tag to enable the dark mode, or theme-light to enable the light mode (default). This can be done by modifying the HTML code of your web page.

Here’s an example of how you can add the class to your HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, shrink-to-fit=no, minimal-ui, viewport-fit=cover">
    <!-- Tabler font & Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest/tabler-icons.min.css">
  </head>
  <body class="theme-dark">
    <h1>Welcome to my website</h1>
    <p>This is an example of dark theme in Tabler.</p>
    <!-- Your website content goes here -->
    <script src="https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/js/tabler.min.js"></script>
  </body>
</html>

Toggle Theme Buttons

To provide a user-friendly way to switch between the light and dark theme, I added two buttons to the header of my web application. These buttons allow the user to quickly toggle between the two themes with just a click. The buttons are styled with icons using the Tabler theme’s built-in icon font, making them a perfect match for the rest of the UI. By adding this simple feature, my web application becomes more accessible and enjoyable to use for users who prefer different color schemes.

<header class="navbar navbar-expand-md navbar-light sticky-top d-print-none">
  <div class="container-xl">
    <div class="navbar-nav flex-row order-md-last">
      <div class="d-md-flex p-2">
        <a class="nav-link px-0 hide-theme-dark" aria-label="Enable dark mode" onclick="toggleTheme()">
          <i class="ti ti-moon ti-size-3"></i>
        </a>
        <a class="nav-link px-0 hide-theme-light" aria-label="Enable light mode" onclick="toggleTheme()">
          <i class="ti ti-sun-high ti-size-3"></i>
        </a>
      </div>
    </div>
  </div>
</header>

Switching Dark and Light Mode with JavaScript

The code I provided uses the localStorage API in JavaScript to store the theme preference of the user. If no theme preference is found in the local storage, it uses the window.matchMedia method to check if the user’s browser has a preference for dark mode. If it does, the theme is set to dark and stored in the local storage. Otherwise, the theme is set to light and stored.

let theme = localStorage.getItem("theme");

if(theme === null) {
    const prefersDarkTheme = window.matchMedia('(prefers-color-scheme: dark)');
    if (prefersDarkTheme.matches) {
        localStorage.setItem("theme", "dark");
        theme = "dark";
    } else {
        localStorage.setItem("theme", "light");
        theme = "light";
    }
}

Then, the code sets the theme class on the body element based on the stored theme preference. If the theme is dark, it removes the theme-light class and adds the theme-dark class. If the theme is light, it removes the theme-dark class and adds the theme-light class.

if (theme === "dark") {
    document.body.classList.remove("theme-light");
    document.body.classList.add("theme-dark");
} else if (theme === "light") {
    document.body.classList.remove("theme-dark");
    document.body.classList.add("theme-light");
}

Finally, the toggleTheme function is used to switch between the light and dark themes. It first gets a reference to the body element and checks if it has the theme-dark class. If it does, it removes that class and adds the theme-light class, sets the theme preference to light in the local storage, and triggers a vibration on mobile devices. If the body element does not have the theme-dark class, it removes the theme-light class and adds the theme-dark class, sets the theme preference to dark in the local storage, and triggers a vibration on mobile devices.

function toggleTheme() {
    const body = document.body;
    if (body.classList.contains("theme-dark")) {
        body.classList.remove("theme-dark");
        body.classList.add("theme-light");
        localStorage.setItem("theme", "light");
        mobileVibrate([50]);
    } else {
        body.classList.remove("theme-light");
        body.classList.add("theme-dark");
        localStorage.setItem("theme", "dark");
        mobileVibrate([50]);
    }
}

Optional Mobile Vibration for UX Enhancement

The mobileVibrate() function is optional and is used to add haptic feedback to the theme switcher button for mobile users. It checks if the user agent is a mobile device and if so, it triggers a vibration using the window.navigator.vibrate() method. The pattern parameter is an array of numbers that defines the duration of vibration and pause in milliseconds. For example, [50] would cause the device to vibrate for 50 milliseconds.

//Vibration Function
function mobileVibrate(pattern) {
    if (window.navigator.userAgentData.mobile) {
        window.navigator.vibrate(pattern);
    }
}

Conclusion

In conclusion, implementing a dark mode in your web application can provide several benefits, including reducing eye strain, saving battery life, and creating a modern and sleek design. However, it’s important to consider accessibility when implementing dark mode, such as ensuring appropriate contrast ratios, text sizes, and other considerations.

To effectively use dark mode, it’s recommended to provide a toggle button for users to switch between light and dark modes, and to store the user’s preference using localStorage. Additionally, using a pre-existing project with theme like Tabler can save time and effort in implementing a consistent and accessible design.

Overall, dark mode is a great addition to any web application, but it’s important to consider accessibility and user preferences to ensure a positive experience for all users.

Explore More about Tabler

You can explore more about Tabler and its features by visiting their website at https://tabler.io/. There, you can find detailed documentation on how to use the theme, a live demo to see it in action, and additional resources. Tabler also has an active community on GitHub where you can contribute to the project or ask for support. So, don’t hesitate to check out the website and discover more about this powerful project.

Similar Posts

Leave a Reply