Post

Add Dark Mode Toggle Component

Implemented a smooth dark mode toggle with system preference detection and localStorage persistence.

Add Dark Mode Toggle Component

Feature Description

Added a beautiful dark mode toggle component that respects system preferences and remembers user choice across sessions.

Implementation

Key Features

  • Smooth transition animations
  • System preference detection
  • localStorage persistence
  • Keyboard accessibility (Space/Enter to toggle)
  • ARIA labels for screen readers
  • No flash on page load

Technical Details

1
2
3
4
5
6
7
8
9
10
11
12
13
// Toggle logic
function toggleDarkMode() {
  const currentMode = document.documentElement.getAttribute('data-mode');
  const newMode = currentMode === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-mode', newMode);
  localStorage.setItem('mode', newMode);
}

// System preference detection
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
if (!localStorage.getItem('mode')) {
  setMode(prefersDark.matches ? 'dark' : 'light');
}

CSS Improvements

  • Added smooth color transitions
  • Optimized color palette for both modes
  • Improved contrast ratios for accessibility
  • Added custom properties for easy theming

User Benefits

  • Better reading experience at night
  • Reduced eye strain
  • Respects user preferences
  • Seamless experience across devices

Pull Request

#1245 - Merged on February 10, 2026

This post is licensed under CC BY 4.0 by the author.

Trending Tags