This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const setTheme = (theme) => { | |
const rootElement = document.querySelector("html"); | |
// Set <html daa-theme="theme"> to change children styles | |
rootElement.setQuery("data-theme", theme); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
NewerOlder