Skip to content

Instantly share code, notes, and snippets.

@arnog
Created January 4, 2019 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnog/f907aeed9ff3916c9091de3b8cadabe7 to your computer and use it in GitHub Desktop.
Save arnog/f907aeed9ff3916c9091de3b8cadabe7 to your computer and use it in GitHub Desktop.
function switchTheme(ev) {
// If the alt/option key is pressed, reset to system default
if (ev.altKey) {
document.getElementsByTagName("BODY")[0].removeAttribute("theme");
return;
}
const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
let theme = document.getElementsByTagName("BODY")[0].getAttribute("theme");
if (theme === "dark") {
theme = "light";
} else if (theme === "light") {
theme = "dark";
} else {
theme = prefersDark ? "light" : "dark";
}
document.getElementsByTagName("BODY")[0].setAttribute("theme", theme);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment