Implementing Adaptive Dark Mode Based on User’s OS Settings: A Step-by-Step Guide

Original Source: https://1stwebdesigner.com/implementing-adaptive-dark-mode-based-on-users-os-settings-a-step-by-step-guide/

More and more users prefer browsing websites in dark mode to reduce eye strain and save battery life. To provide the best user experience, it’s helpful to implement an automatic dark mode on your website that adjusts according to a user’s operating system settings. In this tutorial, we’ll walk you through the steps to achieve this.

Your Web Designer Toolbox
Unlimited Downloads: 500,000+ Web Templates, Icon Sets, Themes & Design Assets
DOWNLOAD NOW

 

1. Create a CSS file for dark mode

First, create a separate CSS file called “darkmode.css” that contains the styles for your website’s dark mode. This file should include the color palette, font styles, and other design elements that cater to dark mode. For example:

body {
background-color: #121212;
color: #ffffff;
}

h1, h2, h3, h4, h5, h6 {
color: #f0f0f0;
}

a {
color: #ffffff;
text-decoration: underline;
}

2. Link the dark mode CSS file

In your website’s main HTML file, add the following link tag inside the head section to reference the dark mode CSS file:

<link id="darkmode-stylesheet" rel="stylesheet" href="darkmode.css" media="(prefers-color-scheme: dark)" />

The “media” attribute ensures that the dark mode CSS file will only be applied if the user’s operating system is set to dark mode.

3. Detect operating system’s color scheme

Now it’s time to detect the user’s operating system color scheme with JavaScript. Create a new JavaScript file called “darkmode.js” and add the following code:

function getSystemColorScheme() {
return window.matchMedia && window.matchMedia(‘(prefers-color-scheme: dark)’).matches ? ‘dark’ : ‘light’;
}

This function checks if the user’s operating system is set to dark mode or light mode by evaluating the ‘prefers-color-scheme’ media query.

4. Save the user’s preference

To improve the user experience, we’ll save their preference in the browser’s local storage. Add the following code to the “darkmode.js” file:

function saveUserPreference(preference) {
localStorage.setItem(‘color-scheme’, preference);
}

function loadUserPreference() {
return localStorage.getItem(‘color-scheme’);
}

These two functions save and load the user’s color scheme preference, respectively.

5. Toggle dark mode

Create a function to toggle dark mode on and off by adding or removing the “dark” class from the HTML body element:

function toggleDarkMode(enableDarkMode) {
if (enableDarkMode) {
document.body.classList.add(‘dark’);
} else {
document.body.classList.remove(‘dark’);
}
}

6. Initialize dark mode based on user preference or system settings

Now, add a function to initialize dark mode on page load. This function checks if the user has a saved preference in local storage; if not, it defaults to their operating system’s settings:

function initializeDarkMode() {
const userPreference = loadUserPreference();

if (userPreference) {
toggleDarkMode(userPreference === ‘dark’);
} else {
const systemColorScheme = getSystemColorScheme();
toggleDarkMode(systemColorScheme === ‘dark’);
}
}

document.addEventListener(‘DOMContentLoaded’, initializeDarkMode);

7. Allow users to toggle dark mode manually

As a fallback and also providing a better experience for your users, it is a good practice to give them the ability to switch between dark and light modes manually. To do this, add a button or a switch element in your website’s main HTML file:

<button id="toggle-darkmode">Toggle Dark Mode</button>

Next, add an event listener for this button in your “darkmode.js” file:

function handleDarkModeToggle() {
const currentPreference = loadUserPreference() || getSystemColorScheme();
const newPreference = currentPreference === ‘dark’ ? ‘light’ : ‘dark’;

toggleDarkMode(newPreference === ‘dark’);
saveUserPreference(newPreference);
}

document.getElementById(‘toggle-darkmode’).addEventListener(‘click’, handleDarkModeToggle);

This function toggles dark mode, saves the new preference in local storage, and updates the user interface.

8. Listen for operating system changes

To ensure that your website’s dark mode adapts to changes in the user’s operating system settings, add an event listener to the “darkmode.js” file that listens for changes to the ‘prefers-color-scheme’ media query:

function handleSystemColorSchemeChange(event) {
if (!loadUserPreference()) {
toggleDarkMode(event.matches);
}
}

window.matchMedia(‘(prefers-color-scheme: dark)’).addListener(handleSystemColorSchemeChange);

This function checks if the user has a saved preference in local storage. If not, it toggles dark mode based on the updated operating system settings.

9. Link the JavaScript file

Finally, include the “darkmode.js” file in your main HTML file by adding the following script tag inside the head section:

<script src="darkmode.js" defer></script>

The “defer” attribute ensures that the script is executed only after the HTML document has been fully parsed.

All done! Now you have everything you need to implement dark mode on your future projects!

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *