Dark Mode Toggle dengan localStorage
JavaScript
#javascript
#dark-mode
#theme
#localStorage
Implementasi dark mode toggle yang persist di localStorage dan respect system preference.
(function () {
const STORAGE_KEY = 'theme';
const html = document.documentElement;
function getPreferred() {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'dark' || stored === 'light') return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function apply(theme) {
html.setAttribute('data-theme', theme);
document.body?.setAttribute('data-theme', theme);
localStorage.setItem(STORAGE_KEY, theme);
}
// Apply immediately (before DOM ready to avoid flash)
apply(getPreferred());
// Toggle button
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('[data-theme-toggle]').forEach(function (btn) {
btn.addEventListener('click', function () {
const current = html.getAttribute('data-theme') || 'light';
apply(current === 'dark' ? 'light' : 'dark');
});
});
});
// Listen for system preference changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function (e) {
if (!localStorage.getItem(STORAGE_KEY)) {
apply(e.matches ? 'dark' : 'light');
}
});
})();
151 views
17 copies
11 jam yang lalu