Skip to content

Simple dark mode implementation

Simple and FOLMBDMKI* is minimized

Tags that this post has been filed under. Links open in the same window.

*Flash Of Light Mode Before Dark Mode Kicks In

const toggle = document.querySelector('.theme-changer');
var storedTheme = localStorage.getItem('theme') || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
if (storedTheme)
document.documentElement.setAttribute('data-theme', storedTheme)

toggle.onclick = function() {
var currentTheme = document.documentElement.getAttribute("data-theme");
var targetTheme = "light";

if (currentTheme === "light") {
targetTheme = "dark";
}

document.documentElement.setAttribute('data-theme', targetTheme)
localStorage.setItem('theme', targetTheme);
};