Lewis Tyler

Simple persistent dark mode switcher with vanilla JavaScript and browser storage

var html = document.documentElement; // Selects the <html> element
var storage = window.localStorage;
var sTheme = storage.getItem('theme');
var theme = html.getAttribute('data-theme');

// Check if the users operating system has has a colour scheme preference
if (!sTheme && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
  html.setAttribute('data-theme', 'dark');
  storage.setItem('theme', 'dark');
}

// Check localstorage to see if use has previously chosen a colour scheme
if (sTheme) {
  html.setAttribute('data-theme', sTheme);
}

// Toggle the scheme by setting [data-theme] and save preference to localstorage
document.querySelector('.theme-switcher button').addEventListener('click', function () {
  theme = html.getAttribute('data-theme');

  if (theme === 'dark') {
    html.setAttribute('data-theme', 'light')
    storage.setItem('theme', 'light');
  } else {
    html.setAttribute('data-theme', 'dark')
    storage.setItem('theme', 'dark');
  }
});