DEV Community

Cover image for How to Detect if a User is in Dark Mode In Js
Avinash Tare
Avinash Tare

Posted on

2 1 1 1 1

How to Detect if a User is in Dark Mode In Js

Introduction

Have you ever wondered how websites seamlessly switch between light and dark modes based on your preferences? It’s not magic—it's a clever use of modern web technologies. In this post, I'll reveal the simple yet powerful technique behind detecting whether a user prefers dark mode and how you can use this information to enhance the user experience on your website.

Understanding Dark Mode Detection

With the popularity of dark mode, many websites and applications now offer themes that align with the user's system preferences. This feature is achieved using the matchMedia API in JavaScript, which allows web applications to respond to changes in media queries, such as the user's color scheme preference.

How it's works

The matchMedia API

The window.matchMedia method provides a way to evaluate media queries and adapt your site's appearance based on the user's preferences. To check if dark mode is enabled, you can use the following JavaScript function:

// Check if the user prefers dark mode
function isDarkMode() {
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}
Enter fullscreen mode Exit fullscreen mode

Practical Implementation

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Dark Mode Demo</title>
    <style>
        .dark {
            background: black;
            color: white;
        }
        .light {
            background: white;
            color: black;
        }
    </style>
</head>
<body>

    <h1>Hello, World!</h1>

    <!-- scripts -->
    <script>
        // Function to check if dark mode is enabled
        function isDarkMode() {
            return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        }

        // Function to update the theme based on the user's preference
        function updateTheme() {
            if (isDarkMode()) {
                document.body.classList.add("dark");
                document.body.classList.remove("light");
            } else {
                document.body.classList.add("light");
                document.body.classList.remove("dark");
            }
        }

        // Initial theme setup
        updateTheme();

        // Listen for changes in the color scheme preference
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateTheme);
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • updateTheme Function: This function checks the dark mode preference and updates the class accordingly. Real-Time Updates: Added an event listener to matchMedia to detect changes in the color scheme preference and call update theme to adjust the appearance in real-time.

When you change your system's color scheme, the website will automatically adapt to reflect your preference without needing to refresh the page.

Follow Me on GitHub Avinash Tare

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay