Easy Ways to Add Dark Mode Functionality with JavaScript
learn how to add Dark Mode using JavaScript
Table of contents
Introducing Dark Mode: Enhance Your Website with JavaScript and CSS
Hey there, friends! Tired of those bright white screens and looking for some relief for your eyes? It's time to welcome the dark side!
Dark mode is the cool trend that's making apps gentler on our eyes. Websites like GitHub, Reddit, Twitter, and Medium have already adopted the dark mode - and now it's your chance!
In this guide, we'll provide you with the JavaScript and CSS know-how to create amazing dark themes for your websites in no time. Just think of it as "midnight mode"! Let's get started.
What is Dark Mode and Why Should You Care?
Dark mode displays content against a dark background rather than a light one. It flips the script by making text light and images dark.
Going dark has some killer benefits:
Saves your eyes from being strained by bright screens
Makes night time browsing easy without disrupting your circadian rhythms
Looks incredibly sleek and stylish
Helps conserve battery life on devices with OLED displays
With all those perks, dark mode is a must-have for any slick site or app! Learning to code themes is worth it.
Gearing Up: Core Skills You'll Need
Before we start slinging code, make sure you have these core skills equipped:
- HTML - For Marking Up Content
HTML provides the structure and semantics for your content. You'll need to know basics like headings, paragraphs, divs, and more.
- CSS - For Styling and Theming
To customize the look and feel, CSS is key. Get familiar with selectors, properties, and precedence.
- JavaScript - For Interactivity
JS will help make our dark mode toggle interactive. Brush up on DOM manipulation, events, and functions.
- A Test Page - For Experiments
Have a simple HTML page with some content ready to tweak for examples.
Locked and loaded with those skills? Then it's go time - let's do this!
Dark Magic Spell #1 - CSS Media Queries
Our first dark arts spell relies solely on CSS by using media queries:
/* Normal styles */
body {
background: white;
color: black;
}
/* Dark mode styles */
@media (prefers-color-scheme: dark) {
body {
background: black;
color: white;
}
}
The prefers-color-scheme
media query detects if the visitor has dark mode enabled in their OS settings. If so, the nested styles override the defaults to apply the dark theme.
This automatically adapts the site to light or dark mode based on their preference. Slick!
But what if they want to toggle manually? Let's add that next with JS.
Dark Magic Spell #2 - JS Powered Toggling
For direct control regardless of system settings, we can add a toggle button with JavaScript:
// Get toggle button
const toggle = document.getElementById('dark-mode-toggle')
// Add click event listener
toggle.addEventListener('click', () => {
// Toggle .dark-mode class on body
document.body.classList.toggle('dark-mode')
})
When clicked, this adds/removes a .dark-mode
class to trigger the theme:
/* Dark mode styles */
body.dark-mode {
background: black;
color: white;
}
Boom! With just a few lines of JS, you can now manually activate dark mode.
Keep in mind this toggles the entire page. You can also selectively style elements.
Magical Toggling - Alternative Methods
A few other slick ways to implement dark mode toggling:
CSS Variables
Use custom properties to store colors and swap values:
:root {
--bg: white;
--text: black;
}
.dark-mode {
--bg: black;
--text: white;
}
Then reference the variables in styles:
body {
background: var(--bg);
color: var(--text);
}
SVG Icons
Dynamically load different SVG icons and color them based on mode:
if (darkMode) {
toggleIcon.src = 'moon.svg'
toggleIcon.style.fill = 'white'
} else {
toggleIcon.src = 'sun.svg'
toggleIcon.style.fill = 'yellow'
}
Separate Headings
Theme headings independently from body for a cooler effect:
h1, h2, h3 {
color: pink; /* stays pink in dark mode */
}
Plenty of inventive approaches if you think outside the box!
Wielding Dark Powers with Libraries
For even more effortless dark sorcery, leverage these JS libraries:
DarkReader
Open source script that auto-generates dark themes for any site
Inverts colors, tweaks contrast, customizable styles
Add via
<script src="darkreader.js">
Solarized Dark
Gorgeous color palette based on iconic Solarized theme
Use
import 'solarized-dark-theme'
Provides CSS variables to reference colors
Darkmode.js
Feature-packed library with auto-toggle, manual toggle, plugins
import Darkmode from 'darkmode-js'
React wrapper also available
Many framework-specific libraries too like React Darkmode, Vue Darkmode, etc. Try a few out!
Mastering the Dark Arts
Once you've grasped the basics, here are some pro tips:
- Pick Easy-on-the-Eyes Colors
Use a palette generator and experiment to find a scheme with sufficient contrast.
- Make Text Legible
Soft off-whites like #F9FAFB display better than harsh #FFFFFF for text.
- Give Users Control
Allow enabling dark mode manually in settings for those who prefer it full time.
- Design Responsively
Test dark mode across screen sizes. Adjust styles for mobile vs desktop.
- Debug Like a Pro
Inspect colors and contrast using DevTools. Toggle classes and set prefers-color-scheme.
- Remember Accessibility
Hide an .sr-only
heading that alerts screen readers when swapping modes.
With great darkness comes great responsibility. Use your skills wisely!
Taking Dark Mode to the Next Level
You've got the basics down, so now it's time for some advanced spells:
- Dynamic Themes
Generate and save multiple themes based on different images.
- Browser Extensions
Create extensions like Dark Reader to inject dark mode on any site.
- Component Libraries
Build reusable React and Vue components for toggles and themes.
- Testing Automation
Write Cypress or Selenium tests that verify dark mode works across pages.
- Persistence Options
Explore LocalStorage, IndexedDB, cookies for saving preferences.
- Global State Management
Manage dark mode globally in large apps with Redux, MobX, etc.
Plenty of opportunities to push dark mode even further!
Join the Dark Side
We've covered a ton of ground here. Let's recap the key points:
What - Dark mode displays content on a dark background.
Why - Less eye strain, better readability, and vampiric vibes.
How - CSS media queries and JS DOM manipulation.
Libraries - Enable customization and advanced features.
Practices - Pick good colors, test responsively, debug carefully.
Beyond Basics - Dynamic themes, browser extensions, testing, persistence.
I don't know about you, but I'm now pumped to crank my projects up to 11 with dark mode!
The world of darkness awaits. Go get coding and save some eyeballs from bright screens everywhere!