Detecting User Dark Mode Preferences with JavaScript

26 May 2023 Balmiki Mandal 0 MERN Full Stack

Detect Dark Mode Preference with JavaScript

More and more people are using dark mode settings on their devices, and as web developers, it's important to give visitors the option to enable dark mode in our own sites. Fortunately, this is easy to do with JavaScript! Here's a guide on how to detect dark mode preference with JavaScript.

1. Detecting dark mode in the OS

The easiest way to detect if a user has enabled dark mode in their operating system is to use the prefers-color-scheme media query. This media query will tell you if the user has enabled dark mode or light mode in their OS setting. Here's an example of how to check if dark mode is enabled:

<script>
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        // The user has enabled dark mode in their OS settings
    } else {
        // The user has not enabled dark mode in their OS settings
    }
</script>

2. Detecting dark mode in the browser

If you want to detect if a user has enabled dark mode preferences in their browser settings, you can use the prefers-color-scheme media query as well. However, you'll also need to check for the support of the prefers-color-scheme media query before attempting to use it. Here's an example of how to check if dark mode is enabled in the browser settings:

<script>
    var mediaQuery = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
    
    if (mediaQuery && mediaQuery.matches) {
        // The user has enabled dark mode in their browser settings
    } else {
        // The user has not enabled dark mode in their browser settings
    }
</script>

3. Changing the UI based on user preference

Once you've detected whether a user has enabled dark mode in either their OS or browser, you can change the color scheme of your site accordingly. Here's an example of how you might go about changing the UI based on user preference:

<script>
    var mediaQuery = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
    
    if (mediaQuery && mediaQuery.matches) {
        document.body.style.backgroundColor = '#000000';
        document.body.style.color = '#ffffff';
    } else {
        document.body.style.backgroundColor = '#ffffff';
        document.body.style.color = '#000000';
    }
</script>

By following the steps outlined in this guide, you can easily detect dark mode preference with JavaScript and dynamically change the UI of your site accordingly. This will allow you to give your users the best possible experience, no matter what device or settings they're using.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.