Skip to content

Instantly share code, notes, and snippets.

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 willmendesneto/fe150b05fda7a6ced2624c1254305515 to your computer and use it in GitHub Desktop.
Save willmendesneto/fe150b05fda7a6ced2624c1254305515 to your computer and use it in GitHub Desktop.
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 && e.target ? e.target : 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) {
toggleSiteTheme();
}
/** 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;
document.getElementById("theme-switch").addEventListener(
/** Using touchstart if is a mobile device.
Otherwise, it will trigger based on the click */
isMobileDevice ? "touchstart" : "click",
toggleSiteTheme
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment