Easy Dark Mode Custom Element – dark-mode

Category: Javascript , Recommended | March 18, 2022
Author:jaywcjlove
Views Total:287 views
Official Page:Go to website
Last Update:March 18, 2022
License:MIT

Preview:

Easy Dark Mode Custom Element – dark-mode

Description:

A Custom Element (<dark-mode />) to create dark/light mode toggle elements on the web application.

It detects OS color scheme settings using the prefers-color-scheme and applies corresponding styles to the page.

In addition, it saves user preference in the local storage and automatically applies Dark or Light mode on the next visit.

How to use it:

1. Install & download the dark-mode.

# NPM
$ npm i @wcj/dark-mode --save

2. Load the main script in the document.

<script src="main.js" defer></script>

3. Add the <dark-mode> Custom Element to the page. That’s it.

<dark-mode></dark-mode>

4. Add a label to the dark/light mode toggler.

<dark-mode light="Dark" dark="Light"></dark-mode>

5. API methods.

const instance = document.querySelector('dark-mode');
// enable dark mode
instance.mode = 'dark';
// or
document.documentElement.setAttribute('data-color-mode', 'dark');
// enable light mode
instance.mode = 'light';
// or
document.documentElement.setAttribute('data-color-mode', 'light');
// Set the mode to dark
// set lable text
instance.light = 'Dark';
instance.dark = 'Light';
instance.permanent = 'on';
// save user preference
darkModeToggle.setAttribute('permanent', false);
// clear user preference
darkModeToggle.removeAttribute('permanent');

6. Events.

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

You Might Be Interested In:


Leave a Reply