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/9e5b57e68b2b032de8212a6083b07019 to your computer and use it in GitHub Desktop.
Save willmendesneto/9e5b57e68b2b032de8212a6083b07019 to your computer and use it in GitHub Desktop.
dark-mode via css media query and classes 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();
}
/** 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