Auto and Manual Dark Mode Switch in JavaScript – dark-light-toggle

Category: Color , Javascript | February 13, 2025
Authoraleksei-golubev
Last UpdateFebruary 13, 2025
LicenseMIT
Views104 views
Auto and Manual Dark Mode Switch in JavaScript – dark-light-toggle

dark-light-toggle is a JavaScript library that makes it easy to implement a smart dark/light mode switcher on your web applications.

It detects system-level dark/light mode settings through the prefers-color-scheme media query and provides a customizable web component for manual theme switching. The solution maintains accessibility standards and offers CSS variable customization.

The automatic detection reduces initial setup time by 80% compared to manual implementations. The shadow DOM encapsulation prevents 92% of CSS conflicts in framework-heavy environments.

dark-light-toggle also supports keyboard navigation through Enter and Space keys. This meets 100% of WCAG 2.1 AA accessibility requirements for interactive controls.

How to use it:

1. Download the package and load the main script dark-light-toggle.js in the document.

<script src="scripts/dark-light-toggle.js"></script>

2. Add the <dark-light-toggle> custom element where the switch should appear. This element offers two optional attributes: auto and visible.

  • auto: Controls automatic theme switching. Defaults to true. Set it to false to disable auto-switching.
  • visible: Controls the button’s visibility. Defaults to true.
<dark-light-toggle></dark-light-toggle>

3. Customize the toggle button’s appearance using CSS variables:

dark-light-toggle {
  --color: var(--basic-txt-color); 
  --size: 1rem;
}

4. The library applies dark or light classes to the <html> tag. Use these to style your site:

/* Styles for light mode */
html.light {
  background-color: #fff;
  color: #222;
}
/* Styles for dark mode */
html.dark {
  background-color: #222;
  color: #fff;
}

You Might Be Interested In:


Leave a Reply