Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
dark-mode via css media query classes and scheme listener via javascript
function toggleSiteTheme(e) {
var html = document.getElementsByTagName("html");
var className = html[0].classList.value;
/** Gets the target by checking if it was triggered by
clicking on the switch or if via OS configuration changes */
var target = document.getElementById("theme-switch");
var isLightMode = target.className === "" || className === "light-mode";
/** Adds the class into our HTML to determine if it will be light or dark mode */
html[0].className = isLightMode ? "dark-mode" : "light-mode";
/** Adds the class into our switch to show the user choices
for light or dark mode is active or not */
target.className = isLightMode ? "active" : "";
/** Checks the input and change the value of it.
So the CSS changes can be applies */
document.getElementById("switch-checkbox").checked = isLightMode
? true
: false;
}
/** Firstly, we should check if window.matchMedia is available
on the user's browser */
const isMatchMediaSupported = typeof window.matchMedia === "function";
/** if it is, we can start the javascript manipulation */
if (isMatchMediaSupported) {
const darkModeMatches = window.matchMedia("(prefers-color-scheme: dark)");
/** Checks if dark mode is enabled via OS on page load,
so it can add the dark-mode class and trigger the
toggle on the switch */
if (darkModeMatches.matches) {
toggleSiteTheme();
}
/** Adds a listener for dark-mode changes in OS */
darkModeMatches.addListener((e) => toggleSiteTheme());
/** Adding a listener for the switch toggle */
document.getElementById("theme-switch")
.addEventListener("click", toggleSiteTheme);
/** If the browser supports it, we can change the switch content
to be visible. Otherwise, it will be hidden via CSS */
document.getElementById("switch-checkbox").style.display = 'flex';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment