Local Storage

A example to remember user’s preferred dark mode setting.

Given a checkbox with id darkmode. When user clicks the checkbox (change event), set the preferrence in localStorage

const osDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
const supportsLocalStorage = 'localStorage' in window
const darkModeCheckbox = document.getElementById('darkmode')

if (supportsLocalStorage) {
  darkModeCheckbox.addEventListener('change', rememberDarkmode)
  const darkMode = localStorage.getItem('yourapp-darkMode')

  if (darkMode !== null) {
    darkModeCheckbox.checked = darkMode === '1'
  } else if (osDarkMode && darkMode === null) {
    darkModeCheckbox.checked = true
  }

  function rememberDarkmode () {
    if (darkModeCheckbox.checked) {
      localStorage.setItem('yourapp-darkMode', '1')
    } else {
      localStorage.setItem('yourapp-darkMode', '0')
    }
  }
}