Dark mode toggle

Bootstrap 5.3 themes switch with one attribute on the html element.

Bootstrap · Dark mode toggleIntermediate
<button type="button" class="btn btn-outline-secondary" id="themeBtn">Toggle theme</button>

<script>
  (function () {
    var root = document.documentElement;
    var saved = null;
    try { saved = localStorage.getItem('theme'); } catch (e) {}
    var prefersDark = window.matchMedia && matchMedia('(prefers-color-scheme: dark)').matches;
    root.setAttribute('data-bs-theme', saved || (prefersDark ? 'dark' : 'light'));

    document.getElementById('themeBtn').addEventListener('click', function () {
      var next = root.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark';
      root.setAttribute('data-bs-theme', next);
      try { localStorage.setItem('theme', next); } catch (e) {}
    });
  })();
</script>
data-bs-themedark modelocalStoragetoggle