Skip to content

Another dark mode implementation

This looks so pretty, but flashes so hard :(

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

function getUserPreference() {
if(window.localStorage.getItem('theme')) {
return window.localStorage.getItem('theme')
}
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
document.documentElement.dataset.theme = getUserPreference();

const toggle = document.querySelector('.theme-changer');
toggle.onclick = function() {
var currentTheme = document.documentElement.dataset.theme
var targetTheme = "light";

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

document.documentElement.dataset.theme = targetTheme
window.localStorage.setItem('theme', targetTheme);
};