Simple CSS Theme (Dark Mode) Toggler In JavaScript

Category: Javascript | August 28, 2021
Views Total:376 views
Official Page:Go to website
Last Update:August 28, 2021


Simple CSS Theme (Dark Mode) Toggler In JavaScript


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 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: –>

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">
.dark-mode-toggle {
  padding: 1em;
  cursor: pointer;
  /* Hide the toggle initially if the user's JS is disabled: */
  visibility: hidden;

5. Initialize the library.

  toggle: document.querySelector(".dark-mode-toggle"),
  classes: {
    light: "light",
    dark: "dark",
  default: "light", // default theme name
  storageKey: "dark_mode_pref",

6. Callback functions.

  onInit: function (toggle) { = "visible";
  onChange: function (theme, toggle) {
    console.log("Theme is now " + theme);

You Might Be Interested In:

Leave a Reply