Customizable Dark Mode Toggle Component In TypeScript

Category: Javascript , Recommended | March 6, 2023
Views Total:574 views
Official Page:Go to website
Last Update:March 6, 2023


Customizable Dark Mode Toggle Component In TypeScript


An easy-to-use yet highly customizable dark mode toggle component written in TypeScript.

It supports prefers-color-scheme media queries, making it easier to automatically adjust to the user’s preferred light or dark color scheme.

Users can also toggle between dark and light modes with a custom switch or toggle button. The component will then save the user’s color preference to local storage, making it easier for them to maintain their preferred mode.

How to use it:

1. Install & download.

$ npm i dark-mode-toggle

2. Import the dark mode toggle component as a module.

<script type="module" src=""></script>

3. Add the dark-mode-toggle component to the page. Available props:

  • id: Unique ID
  • legend: Legend for the toggle or switch.
  • appearance: “switch” or “toggle”
  • dark: Dark label
  • light: Light label
  • remember: remember label
  • mode: “dark” or “light”
  • permanent: true or false
  legend="Dark mode Switcher"
  remember="Remember This"

4. Add dark & light stylesheets to the page.

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

5. API methods.

const darkModeToggle = document.querySelector('dark-mode-toggle');
// Set to dark mode
darkModeToggle.mode = 'dark';
// Set to light mode
darkModeToggle.mode = 'light';
// Set the legend
darkModeToggle.legend = 'Dark Mode';
// Set the light label
darkModeToggle.light = 'off';
// Set the dark label
darkModeToggle.dark = 'on';
// Set the appearance 
darkModeToggle.appearance = 'switch';
darkModeToggle.appearance = 'toggle';
// Set the remember label
darkModeToggle.remember = 'Remember this';
// Remember the user's last color scheme choice
darkModeToggle.setAttribute('permanent', '');
// Forget the user's last color scheme choice

6. Events.

document.addEventListener('colorschemechange', (e) => {
  console.log(`Color scheme changed to ${e.detail.colorScheme}.`);
document.addEventListener('permanentcolorscheme', (e) => {
    `${e.detail.permanent ? 'R' : 'Not r'}emembering the last selected mode.`,

7. Available CSS variables that can be used to customize the appearance of the dark mode toggle.

  • –dark-mode-toggle-light-icon
  • –dark-mode-toggle-dark-icon
  • –dark-mode-toggle-icon-size
  • –dark-mode-toggle-remember-icon-checked
  • –dark-mode-toggle-remember-icon-unchecked
  • –dark-mode-toggle-color
  • –dark-mode-toggle-background-color
  • –dark-mode-toggle-legend-font
  • –dark-mode-toggle-label-font
  • –dark-mode-toggle-remember-font
  • –dark-mode-toggle-icon-filter
  • –dark-mode-toggle-remember-filter
  • –dark-mode-toggle-active-mode-background-color

You Might Be Interested In:

Leave a Reply