<html class="light">
  <head>
    <meta name="color-scheme" content="light dark" />
  </head>
  <body class="light">
    Hello!<br/>
    This is an example for theme toggler.<br/>

    It still works with inputs and other native elements: <input type="date"> <br/>
    
    <span id="theme">light</span> <button id="theme-toggle">Change mode</button><br/><br/>
    
    Pick the "dark" theme and click on rerun button
  </body>
</html>
body.light {
  --text: dark;
  --background: white;
}
body.dark {
  --text: white;
  --background: black;
}

body {
  color: var(--text);
  background: var(--background);
}
function getTheme() {
  return localStorage.getItem('theme') || 'light';
}
function saveTheme(theme) {
  localStorage.setItem('theme', theme);
}

const colorScheme = document.querySelector('meta[name="color-scheme"]');
function applyTheme(theme) {
  document.body.className = theme;
  colorScheme.content = theme;
}

function rotateTheme(theme) {
  if (theme === 'light') {
    return 'dark'
  }
  return 'light';
}

const themeDisplay = document.getElementById('theme');
const themeToggler = document.getElementById('theme-toggle');

// Mimic heavy load done by other JS scripts
setTimeout(() => {
  let theme = getTheme();
  applyTheme(theme);
  themeDisplay.innerText = theme;

  themeToggler.onclick = () => {
    const newTheme = rotateTheme(theme);
    applyTheme(newTheme);
    themeDisplay.innerText = newTheme;
    saveTheme(newTheme);

    theme = newTheme;
  }
}, 100);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.