Navigation & Accessibility

Free Dark Mode Toggle Widget

A sun/moon pill that lets visitors switch your site between light and dark.

A compact sun/moon toggle that adds or removes a class on your page’s <html> element, remembers each visitor’s choice in localStorage, and respects their operating system’s light or dark preference on first visit. Your own CSS styles the dark theme via that class — the widget renders only the toggle pill, so it fits any design. Install it with a single script tag wherever you want the pill to appear.

Live demo

Embed this widget

Paste either snippet into your page — a Custom HTML block on WordPress, Shopify, or Squarespace works too. Both snippets update live as you customize, so what you copy is exactly what you configured.

Hosted (recommended)html
<script src="https://hayneslab.dev/widgets/dark-mode-toggle.js" async></script>
<!-- Free Dark Mode Toggle widget by haynes lab — https://hayneslab.dev/tools/widgets/dark-mode-toggle -->
Inline (self-contained)html
<!-- Free Dark Mode Toggle widget by haynes lab — https://hayneslab.dev/tools/widgets/dark-mode-toggle -->
<script>
/*!
 * haynes lab — Dark Mode Toggle widget (free)
 * Docs & embed code: https://hayneslab.dev/tools/widgets/dark-mode-toggle
 *
 * The widget renders only the sun/moon toggle pill. It adds or removes a class
 * (data-hl-class, default "hlw-dark") on the <html> element — your site's own
 * CSS styles the dark theme via that class, e.g. `.hlw-dark body { ... }`.
 */
(function () {
  'use strict';

  var PREFIX = 'hlw-dark-mode-toggle';
  var STYLE_ID = 'hlw-dark-mode-toggle-styles';
  var STORAGE_KEY = 'hlw-dark-mode-toggle';

  function findScript() {
    return document.currentScript ||
      document.querySelector('script[src*="widgets/dark-mode-toggle.js"]');
  }

  function injectStyles() {
    if (document.getElementById(STYLE_ID)) return;
    var css =
      '.' + PREFIX + ', .' + PREFIX + ' * { box-sizing: border-box; }' +
      '.' + PREFIX + ' { display: inline-flex; align-items: center;' +
      ' font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;' +
      ' font-size: 14px; line-height: 1; color: #1f2937; }' +
      '.' + PREFIX + '__btn { appearance: none; border: 1px solid #e5e7eb; background: #ffffff;' +
      ' border-radius: 999px; cursor: pointer; padding: 3px; width: 52px; height: 28px;' +
      ' display: inline-flex; align-items: center; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);' +
      ' transition: background 0.2s ease, border-color 0.2s ease; }' +
      '.' + PREFIX + '__btn:hover { border-color: var(--hlw-accent); }' +
      '.' + PREFIX + '__btn:focus-visible { outline: 2px solid var(--hlw-accent); outline-offset: 2px; }' +
      '.' + PREFIX + '__knob { width: 20px; height: 20px; border-radius: 50%; background: #f3f4f6;' +
      ' border: 1px solid #e5e7eb; display: inline-flex; align-items: center; justify-content: center;' +
      ' color: #b45309; transform: translateX(0); transition: transform 0.2s ease, background 0.2s ease, color 0.2s ease; }' +
      '.' + PREFIX + '__btn[aria-checked="true"] { background: #111827; border-color: #111827; }' +
      '.' + PREFIX + '__btn[aria-checked="true"] .' + PREFIX + '__knob { transform: translateX(22px);' +
      ' background: #1f2937; border-color: #374151; color: #fbbf24; }' +
      '.' + PREFIX + '__knob svg { display: block; }' +
      '.' + PREFIX + '__credit { font-size: 11px; margin-left: 8px;' +
      ' display: inline-flex; align-items: center; gap: 4px; color: #9ca3af; text-decoration: none; }' +
      '.' + PREFIX + '__credit svg { display: block; }' +
      '.' + PREFIX + '__credit:hover { color: #6b7280; text-decoration: underline; }' +
      '@media (max-width: 480px) { .' + PREFIX + '__credit span { display: none; }' +
      ' .' + PREFIX + '__credit { margin-left: 6px; } }';
    var style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = css;
    document.head.appendChild(style);
  }

  function el(tag, className, text) {
    var node = document.createElement(tag);
    if (className) node.className = className;
    if (text != null) node.textContent = text;
    return node;
  }

  function logoSvg() {
    var svgNS = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(svgNS, 'svg');
    svg.setAttribute('viewBox', '0 0 32 32');
    svg.setAttribute('width', '13');
    svg.setAttribute('height', '13');
    svg.setAttribute('aria-hidden', 'true');
    svg.setAttribute('focusable', 'false');
    function circle(cx, cy, r, attrs) {
      var c = document.createElementNS(svgNS, 'circle');
      c.setAttribute('cx', cx);
      c.setAttribute('cy', cy);
      c.setAttribute('r', r);
      for (var key in attrs) c.setAttribute(key, attrs[key]);
      svg.appendChild(c);
    }
    circle(16, 16, 16, { fill: '#0f0a0a' });
    circle(16, 16, 12, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1, opacity: 0.3 });
    circle(16, 16, 9, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1, opacity: 0.5 });
    circle(16, 16, 6, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1.2, opacity: 0.9 });
    circle(16, 16, 3, { fill: '#06b6d4' });
    circle(24.5, 7.5, 2, { fill: '#f97316' });
    circle(7, 16, 1.8, { fill: '#f97316' });
    circle(20, 20, 1.5, { fill: '#f97316' });
    return svg;
  }

  function iconSvg(dark) {
    var svgNS = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(svgNS, 'svg');
    svg.setAttribute('viewBox', '0 0 24 24');
    svg.setAttribute('width', '12');
    svg.setAttribute('height', '12');
    svg.setAttribute('aria-hidden', 'true');
    svg.setAttribute('focusable', 'false');
    svg.setAttribute('fill', 'none');
    svg.setAttribute('stroke', 'currentColor');
    svg.setAttribute('stroke-width', '2');
    svg.setAttribute('stroke-linecap', 'round');
    svg.setAttribute('stroke-linejoin', 'round');
    var path = document.createElementNS(svgNS, 'path');
    // Sun or moon, both from the same stroke style so the swap is clean.
    path.setAttribute('d', dark
      ? 'M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z'
      : 'M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 1v2M12 21v2M4.2 4.2l1.4 1.4M18.4 18.4l1.4 1.4M1 12h2M21 12h2M4.2 19.8l1.4-1.4M18.4 5.6l1.4-1.4');
    svg.appendChild(path);
    return svg;
  }

  function readStored() {
    try {
      var v = window.localStorage.getItem(STORAGE_KEY);
      if (v === 'dark' || v === 'light') return v;
    } catch (e) { /* storage unavailable */ }
    return null;
  }

  function store(mode) {
    try {
      window.localStorage.setItem(STORAGE_KEY, mode);
    } catch (e) { /* storage unavailable */ }
  }

  function prefersDark() {
    try {
      return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    } catch (e) {
      return false;
    }
  }

  function build(script) {
    var className = script.getAttribute('data-hl-class') || 'hlw-dark';
    var accent = script.getAttribute('data-hl-accent') || '#f97316';
    var root = document.documentElement;

    injectStyles();

    var wrap = el('div', PREFIX);
    wrap.style.setProperty('--hlw-accent', accent);

    var btn = el('button', PREFIX + '__btn');
    btn.type = 'button';
    btn.setAttribute('role', 'switch');
    btn.setAttribute('aria-label', 'Toggle dark mode');
    var knob = el('span', PREFIX + '__knob');
    btn.appendChild(knob);
    wrap.appendChild(btn);

    var isDark = false;

    function apply(dark, persist) {
      isDark = dark;
      root.classList.toggle(className, dark);
      btn.setAttribute('aria-checked', dark ? 'true' : 'false');
      btn.title = dark ? 'Switch to light mode' : 'Switch to dark mode';
      while (knob.firstChild) knob.removeChild(knob.firstChild);
      knob.appendChild(iconSvg(dark));
      if (persist) store(dark ? 'dark' : 'light');
    }

    btn.addEventListener('click', function () {
      apply(!isDark, true);
    });

    // Initial state: saved choice wins, otherwise follow the OS preference.
    var saved = readStored();
    apply(saved ? saved === 'dark' : prefersDark(), false);

    // Follow OS changes only while the visitor has not made an explicit choice.
    if (window.matchMedia) {
      try {
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function (e) {
          if (!readStored()) apply(e.matches, false);
        });
      } catch (e) { /* older browsers */ }
    }

    var credit = el('a', PREFIX + '__credit');
    credit.appendChild(logoSvg());
    var creditText = el('span', null, 'Powered by haynes lab');
    credit.appendChild(creditText);
    credit.href = 'https://hayneslab.dev/tools/widgets/dark-mode-toggle';
    credit.target = '_blank';
    credit.rel = 'noopener';
    wrap.appendChild(credit);

    if (script.parentNode && script.parentNode.nodeName !== 'HEAD') {
      script.insertAdjacentElement('afterend', wrap);
    } else {
      document.body.appendChild(wrap);
    }
  }

  function init() {
    var script = findScript();
    if (!script) {
      console.warn('[haynes lab dark-mode-toggle] Could not locate its own script tag. Nothing rendered.');
      return;
    }
    build(script);
  }

  if (document.body) {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }
})();

</script>

Configuration

Every option is an attribute on the script tag — the same attributes the customizer above exposes. All attributes are optional unless marked required — defaults apply when omitted.

AttributeDefaultDescription
data-hl-class"hlw-dark"Class added to the <html> element while dark mode is on — your CSS styles the dark theme via this class.
data-hl-accent"#f97316"Highlight color for hover and focus states on the pill.

Frequently asked questions

How do I install the Dark Mode Toggle?

Paste the script snippet where you want the pill to appear — it renders an inline sun/moon switch right after the tag and immediately starts toggling the theme class on <html>.

How do I style my site for dark mode?

The widget only adds or removes a class (default hlw-dark) on <html>; write your dark theme in your own CSS, e.g. `.hlw-dark body { background: #111; color: #eee; }`. Rename the class with data-hl-class and set data-hl-accent for the pill’s highlight color.

Does it work on WordPress, Shopify, or Squarespace?

Yes — it is a single vanilla JS file with no dependencies, so it works on WordPress, Shopify, Squarespace, or any site that can embed a script tag.

More free widgets

Need a custom widget?

We build custom widgets, integrations, and whole products. Tell us what your site needs and we'll scope it.

Get in Touch