Author: | jakejarvis |
---|---|
Views Total: | 379 views |
Official Page: | Go to website |
Last Update: | August 28, 2021 |
License: | MIT |
Preview:

Description:
A JavaScript library that enables an HTML element to switch between CSS themes (typically Dark Theme & Light Theme) on your website.
It saves the currently selected theme into the local storage, so only browsers that support localStorage will auto-set the correct theme on the next visit.
In addition, the library detects your OS settings and automatically sets light and dark themes based on your system preferences.
See also:
How to use it:
1. Install and import it with NPM.
# Yarn $ yarn add @jakejarvis/dark-mode # NPM $ npm i @jakejarvis/dark-mode --save
import { init } from "@jakejarvis/dark-mode";
2. Or include the UMD version of the library on the page.
<script src=”./dist/dark-mode.min.js”></script>
<!– or use CDN: https://unpkg.com/@jakejarvis/dark-mode/dist/dark-mode.min.js –>
3. Define your own dark and light themes in the CSS.
/* Light theme */ body.light { background-color: #fff; color: #222; } body.light a { color: #06f; } /* Dark theme */ body.dark { background-color: #222; color: #fff; } body.dark a { color: #fe0; }
4. Create a toggle button to switch between Dark & Light themes.
<button class="dark-mode-toggle"> Toggle </button>
.dark-mode-toggle { padding: 1em; cursor: pointer; /* Hide the toggle initially if the user's JS is disabled: */ visibility: hidden; }
5. Initialize the library.
window.darkMode.init({ toggle: document.querySelector(".dark-mode-toggle"), classes: { light: "light", dark: "dark", }, default: "light", // default theme name storageKey: "dark_mode_pref", });
6. Callback functions.
window.darkMode.init({ onInit: function (toggle) { toggle.style.visibility = "visible"; }, onChange: function (theme, toggle) { console.log("Theme is now " + theme); }, });