Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
dark-mode via css media query classes and scheme listener and event listener optimized by device via javascript
function toggleSiteTheme(e) {
const html = document.getElementsByTagName("html");
const 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 */
const target =
e && ? : document.getElementById("theme-switch");
const 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) {
/** Adds a listener for dark mode changes in OS */
darkModeMatches.addListener((e) => 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';
/** Checks if it's a mobile device or not */
const isMobileDevice =
typeof window.orientation !== "undefined" ||
navigator.userAgent.indexOf("IEMobile") !== -1;
/** Using touchstart if is a mobile device.
Otherwise, it will trigger based on the click */
isMobileDevice ? "touchstart" : "click",
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment