Author: | ColinEspinas |
---|---|
Views Total: | 2,447 views |
Official Page: | Go to website |
Last Update: | January 23, 2020 |
License: | MIT |
Preview:

Description:
darken.js is a lightweight (2.5kb minified) JavaScript library that makes it easier to enable Dark Mode on your page using CSS variables.
It uses CSS prefers-color-scheme to detect if the user has requested the system use a light or dark color theme and saves the user preference in the browser’s local storage.
How to use it:
1. Install and import the darken as a module.
# NPM $ npm install darken --save
import darken from 'darken';
2. Or directly load the umd version of the darken in the document.
<script src="dist/darken.umd.js"></script> <!-- OR FROM A CDN --> <script src="//unpkg.com/darken"></script>
3. Create a button to toggle the dark mode.
<button id="toggle">Toggle Darkmode</button>
4. Initialize the darken library and determine the variables used for the dark/light theme.
const darkmode = new darken({ toggle: "#toggle", variables : { "--primary-color" : ["#ffffff", "#000000"], "--secondary-color" : ["#000000", "#ffffff"], } });
5. Declare variables in the CSS selectors.
body { background-color: var(--primary-color); } h1 { color: var(--secondary-color); }
6. Set the default mode to activate on page load. Default: ‘light’.
const darkmode = new darken({ toggle: "#toggle", variables : { "--primary-color" : ["#ffffff", "#000000"], "--secondary-color" : ["#000000", "#ffffff"], }, default: "dark" });
7. Determine the container to be affected by the darken. Defaults to the whole body.
const darkmode = new darken({ toggle: "#toggle", variables : { "--primary-color" : ["#ffffff", "#000000"], "--secondary-color" : ["#000000", "#ffffff"], }, container: null });
8. Override the default value of storage name.
const darkmode = new darken({ toggle: "#toggle", variables : { "--primary-color" : ["#ffffff", "#000000"], "--secondary-color" : ["#000000", "#ffffff"], }, remember: "darken-mode" });
9. Determine whether or not to use the prefers-color-scheme to get the user preference. Default: true.
const darkmode = new darken({ toggle: "#toggle", variables : { "--primary-color" : ["#ffffff", "#000000"], "--secondary-color" : ["#000000", "#ffffff"], }, usePrefersColorScheme: true });
10. Override the default CSS class applied to the selected container.
const darkmode = new darken({ toggle: "#toggle", variables : { "--primary-color" : ["#ffffff", "#000000"], "--secondary-color" : ["#000000", "#ffffff"], }, class: "darken" });
11. Toggle the dark mode manually.
darkmode.toggle(); darkmode.on(); darkmode.off();
12. Execute a function after switching between dark and light modes.
const darkmode = new darken(function(active) { if (active) console.log("Dark mode is active"); else console.log("Light mode is active"); });