DEV Community

Cover image for Toggle Between Dark/Light Modes with HTML5 web storage API
Mateus V. Farias
Mateus V. Farias

Posted on • Updated on

Toggle Between Dark/Light Modes with HTML5 web storage API

Dark-theme is a really simple dark mode library that enables a switcher to toggle between dark and light modes on the web application.

Written in vanilla JavaScript. Uses HTML5 web storage API (local storage) to save the current theme on the client-side.

How to use it:

Create a checkbox based toggle switch on the page.

<div class="toggle">
  <input id="switch" type="checkbox" name="theme">
  <label for="switch">Toggle</label>
Enter fullscreen mode Exit fullscreen mode
  height: 0;
  width: 0;
  visibility: hidden;

label {
  cursor: pointer;
  text-indent: -9999px;
  width: 52px;
  height: 27px;
  background: grey;
  float: right;
  border-radius: 100px;
  position: relative;

  content: '';
  position: absolute;
  top: 3px;
  left: 3px;
  width: 20px;
  height: 20px;
  background-color: white;
  border-radius: 90px;
  transition: 0.3s;

input:checked + label {
  background-color: var(--color-headings);

input:checked + label::after {
  left: calc(100% - 5px);
  transform: translateX(-100%);

label:active:after {
  width: 45px;
Enter fullscreen mode Exit fullscreen mode

Determine the styles on the light mode using the following CSS variables.

html {
  --bg: #FCFCFC;

body {
  background-color: var(--bg);
Enter fullscreen mode Exit fullscreen mode

The main JavaScript to enable the dark mode switcher and determine the CSS styles on the dark mode.

const html = document.querySelector("html")
const checkbox = document.querySelector("input[name=theme]")

const getStyle = (element, style) => 

const initialColors = {
  bg: getStyle(html, "--bg"),

const darkMode = {
  bg: "#333333", // override styles here

const transformKey = key => 
  "--" + key.replace(/([A-Z])/, "-$1").toLowerCase();

const changeColors = (colors) => {
  Object.keys(colors).map(key =>, colors[key]) 

checkbox.addEventListener("change", ({target}) => {
    target.checked ? changeColors(darkMode) : changeColors(initialColors);
Enter fullscreen mode Exit fullscreen mode

Create local storage.

const isExistLocalStorage = (key) => localStorage.getItem(key) != null;

const createOrEditLocalStorage = (key, value) =>
  localStorage.setItem(key, JSON.stringify(value));

const getValeuLocalStorage = (key) => JSON.parse(localStorage.getItem(key));

checkbox.addEventListener("change", ({ target }) => {
  if (target.checked) {
    createOrEditLocalStorage("mode", "darkMode");
  } else {
    createOrEditLocalStorage("mode", "initialColors");

if (!isExistLocalStorage("mode"))
  createOrEditLocalStorage("mode", "initialColors");

if (getValeuLocalStorage("mode") === "initialColors") {
} else {
  checkbox.setAttribute("checked", "");
Enter fullscreen mode Exit fullscreen mode

Now, try it!

Top comments (0)