Automatic Dark Mode Switcher – darkmode.js

Category: Javascript , Recommended | February 8, 2020
Author:nickdeny
Views Total:3,169 views
Official Page:Go to website
Last Update:February 8, 2020
License:MIT

Preview:

Automatic Dark Mode Switcher – darkmode.js

Description:

darkmode.js is a smart dark mode switcher that automatically switches between dark theme of light theme of your page based on the user’s local time and system scheme.

How to use it:

1. Prepare dark and light themes for your web page.

/* dark.css */
body {
  color: #fff;
  background-color: #222;
}
/* light.css */
body {
  color: #222;
  background-color: #fff;
}

2. Enable the light theme when the user turns off the JavaScript.

<noscript>
  <link rel="stylesheet" href="light.css" />
</noscript>

3. Download the load the darkmode.js script at the end of the document.

<script src="dist/darkmode.min.js"></script>

4. Initialize the library and define the path to the dark & light themes:

var DarkMode = new DarkMode({
    light: "light.css",
    dark: "dark.css"
});

5. Set the time period to enable dark mode.

var DarkMode = new DarkMode({
    light: "light.css",
    dark: "dark.css",
    startAt: '21:00',
    endAt: '06:00'
});

6. Enable a button to toggle the dark mode manually.

var ModeToggler = document.getElementById('myToggler');
ModeToggler.onclick = function() {
  DarkMode.toggleMode()
}

7. Autosave the current mode using the local storage. Default: true.

var DarkMode = new DarkMode({
    light: "light.css",
    dark: "dark.css",
    saveOnToggle: true
});

8. Determine whether to check the system scheme on init. Default: true.

var DarkMode = new DarkMode({
    light: "light.css",
    dark: "dark.css",
    checkSystemScheme: true
});

9. More API methods.

// Get the current mode
DarkMode.getMode();
// Set mode
DarkMode.setMode("light"/"dark");
// Check if the current mode is saved in the local storage
isModeSaved();
// Clear the local storage
DarkMode.clearSavedMode();
// Get the system scheme: light/dark/auto
DarkMode.getSystemScheme();

You Might Be Interested In:


Leave a Reply