UNPKG

dark-mode-toggle-lite

Version:

A lightweight and customizable dark mode toggle for any frontend project

41 lines (35 loc) 1.25 kB
export function initDarkModeToggle(options = {}) { const target = options.target || document.documentElement; const existingBtn = document.querySelector(options.buttonSelector); const toggleTheme = () => { const current = target.getAttribute("data-theme") === "dark" ? "light" : "dark"; target.setAttribute("data-theme", current); if (!options.buttonSelector) { btn.innerText = current === "dark" ? "☀️" : "🌙"; } }; // If a custom button is provided if (existingBtn) { existingBtn.addEventListener("click", toggleTheme); return; } // Otherwise, create default button const btn = document.createElement("button"); btn.innerText = "🌙"; btn.style.position = "fixed"; btn.style.top = "10px"; btn.style.right = "10px"; btn.style.zIndex = "1000"; btn.style.padding = "6px 10px"; btn.style.border = "none"; btn.style.borderRadius = "6px"; btn.style.background = "#eee"; btn.style.cursor = "pointer"; btn.style.fontSize = "18px"; btn.onclick = toggleTheme; document.body.appendChild(btn); // Set default theme if not already set if (!target.getAttribute("data-theme")) { target.setAttribute("data-theme", "light"); } }