Skip to content

Instantly share code, notes, and snippets.

View AhmetEnesKCC's full-sized avatar
🖥️
Coding...

Ahmet Enes KCC AhmetEnesKCC

🖥️
Coding...
View GitHub Profile
@AhmetEnesKCC
AhmetEnesKCC / watchSystemTheme.js
Created March 19, 2022 13:05
watch system theme
const watchSystemTheme = (cb) => { // I will use callback for that
// Addlistener to matchmedia for light and dark mode
window.matchMedia("(prefers-color-scheme: dark)").addListener(e => {
e.matches && cb("dark"); // If it is dark we called the defined callback with dark argument
})
window.matchMedia("(prefers-color-scheme: light)").addListener(e => {
e.matches && cb("light"); // Else If it is dark we called the defined callback with light argument
})
}
const setTheme = (theme) => {
const rootElement = document.querySelector("html");
// Set <html daa-theme="theme"> to change children styles
rootElement.setQuery("data-theme", theme);
}
@AhmetEnesKCC
AhmetEnesKCC / getSystemTheme.js
Last active March 19, 2022 13:01
get system theme
const getSystemTheme = () => {
// Check if the preferred scheme is dark
const isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches; // Be careful! Not just parantheses and quotes, like ("()") this
const mode = isDarkmode ? "dark" : "light";
return mode;
}