javascript
Check if dark mode is enabled using Javascript
In this post, we can learn how to check if dark mode is enabled on the system or not using javascript code.
const dark_mode_enabled = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(dark_mode_enabled());
Output
true
The above Javascript code will return true if the dark mode theme is enabled on the system and returns false if dark mode is not enabled. You can apply your CSS and JS code after that to make your application open in dark mode.
If you want to put it into a condition then you can use the below code.
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
// Do something here...
}
If you want to detect the changes when the user is changing the theme mode then you can apply event listener on that.
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
if (event.matches) {
console.log("DARK MODE IS ENABLED");
} else {
console.log("LIGHT MODE IS ENABLED");
}
});
The below code returns true if dark mode is enabled.
window.matchMedia('(prefers-color-scheme: dark)').matches
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.getElementsByTagName("body")[0].classList.add("dark");
}
Here we are adding a class that has a name dark to the body tag of our web page.
Was this helpful?
Similar Posts
- Add a CSS class to element if dark mode is enabled using Javascript
- Check if a string is Palindrome or not using Javascript
- Check whether a checkbox is checked or not using Javascript only
- Methods to check empty array using javascript
- Check if a number is odd or even using Javascript
- Check if video is stopped or playing Javascript only
- Check if a variable is null, empty, undefined or false Javascript