Detecting Dark Mode Preferences and Switching Styles Using jQuery
Introduction
With the rise of dark mode in modern web applications, providing users with an automatic theme detection and switching mechanism enhances both usability and user experience. Some users prefer dark mode for better readability, while others prefer light mode.
In this guide, we’ll cover:
✅ Detecting system-wide dark mode preferences using the window.matchMedia
API.
✅ Automatically switching between dark and light mode based on user preference.
✅ Using jQuery to manually toggle between modes while also saving the selection in localStorage
.
✅ Adding smooth transitions and animations for a better user experience.
✅ Ensuring accessibility and performance optimization.
By the end of this guide, you’ll have a fully functional theme switcher that adapts to system settings and user preferences.
Table of Contents
- Understanding Dark Mode and User Preferences
- Setting Up the HTML Structure
- Creating CSS Styles for Light and Dark Modes
- Detecting System Preferences Using JavaScript
- Implementing jQuery for Manual Theme Switching
- Saving User Preferences with localStorage
- Adding Smooth Transitions for Better UX
- Enhancing the Theme Switcher with Icons
- Ensuring Accessibility and Performance Optimization
- Final Thoughts and Future Improvements
1. Understanding Dark Mode and User Preferences
Why Implement Dark Mode Detection?
- Many modern operating systems (Windows, macOS, Android, iOS) provide a dark mode option that users can enable.
- Websites can detect this preference and apply the corresponding styles automatically.
- Google recommends dark mode as it reduces eye strain and improves readability in low-light environments.
How Does Dark Mode Detection Work?
- The
window.matchMedia('(prefers-color-scheme: dark)')
API helps detect the user’s OS-level preference. - If a user manually switches themes, we need to save their preference using
localStorage
.
🔹 Goal: Implement an auto-detect feature + a manual toggle button for users.
2. Setting Up the HTML Structure
Create a simple HTML file with a theme toggle button.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dark Mode Detection & Switching</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Dark Mode Detection & Switching</h1>
<p>This page automatically detects dark mode preferences.</p>
<button id="toggle-theme">Switch Theme</button>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Explanation
- A container wraps the content.
- A button (
#toggle-theme
) will let users manually switch themes.
3. Creating CSS Styles for Light and Dark Modes
Define separate CSS themes.
styles.css
/* Default Light Mode */
body {
font-family: Arial, sans-serif;
background-color: #ffffff;
color: #000000;
text-align: center;
padding: 20px;
transition: all 0.5s ease-in-out;
}
/* Dark Mode */
.dark-theme {
background-color: #1e1e1e;
color: #ffffff;
}
/* Button Styles */
button {
margin: 10px;
padding: 10px 20px;
font-size: 16px;
border: none;
cursor: pointer;
border-radius: 5px;
background-color: #0080ff;
color: #fff;
}
button:hover {
opacity: 0.8;
}
Key Features
- Smooth transitions for a better experience.
- Button styling for consistency.
4. Detecting System Preferences Using JavaScript
Use window.matchMedia()
to check if the user prefers dark mode.
script.js
$(document).ready(function () {
function detectSystemTheme() {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
$("body").addClass("dark-theme");
}
}
detectSystemTheme();
});
How It Works
- If the user has dark mode enabled on their system, we add the
.dark-theme
class. - If the user prefers light mode, no changes are needed (light mode is default).
5. Implementing jQuery for Manual Theme Switching
Now, we allow users to manually toggle between dark and light mode.
Updated script.js
$(document).ready(function () {
function detectSystemTheme() {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
$("body").addClass("dark-theme");
}
}
function toggleTheme() {
$("body").toggleClass("dark-theme");
let theme = $("body").hasClass("dark-theme") ? "dark" : "light";
localStorage.setItem("theme", theme);
}
$("#toggle-theme").click(function () {
toggleTheme();
});
detectSystemTheme();
});
6. Saving User Preferences with localStorage
To persist user selection, save the theme in localStorage
.
Updated script.js
$(document).ready(function () {
function applyTheme(theme) {
if (theme === "dark") {
$("body").addClass("dark-theme");
} else {
$("body").removeClass("dark-theme");
}
}
function toggleTheme() {
let newTheme = $("body").hasClass("dark-theme") ? "light" : "dark";
applyTheme(newTheme);
localStorage.setItem("theme", newTheme);
}
$("#toggle-theme").click(function () {
toggleTheme();
});
let savedTheme = localStorage.getItem("theme");
if (savedTheme) {
applyTheme(savedTheme);
} else {
detectSystemTheme();
}
function detectSystemTheme() {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
applyTheme("dark");
}
}
});
🔹 Now, the selected theme persists after page reload!
7. Adding Smooth Transitions for Better UX
Modify styles.css:
body {
transition: background-color 0.5s ease-in-out, color 0.5s ease-in-out;
}
🔹 Ensures a smooth transition between themes.
8. Enhancing the Theme Switcher with Icons
Use Font Awesome for icons.
Updated HTML
<button id="toggle-theme"><i class="fas fa-moon"></i> Toggle Theme</button>
Include Font Awesome
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
9. Ensuring Accessibility and Performance Optimization
- Use high contrast colors.
- Optimize jQuery execution to prevent unnecessary reflows.
10. Final Thoughts and Future Improvements
✅ We built a system that:
- Automatically detects dark mode.
- Allows manual toggling with jQuery.
- Persists user preferences with localStorage.
- Enhances user experience with smooth transitions.
Future Enhancements:
- Add a color picker for custom themes.
- Implement device synchronization for cross-browser consistency.
Now your website dynamically adapts to dark mode preferences!