How to Detect Dark Mode Using JavaScript
Detecting dark mode and mode changes using JavaScript
CSS provides a way to detect dark mode using the prefers-color-scheme media query. But what if we need to use JavaScript? I recently encountered this problem when I had JavaScript code that needed to show a different image based on the light or dark mode.
Here’s how we can approach it:
First, we need to check if the
matchMediaobject exists to determine if the browser supports dark mode. If it doesn’t, we can fall back to light mode.To check if it’s dark mode, we can use the following code:
1
window.matchMedia('(prefers-color-scheme: dark)').matches
This code will return
trueif dark mode is enabled.Let’s consider a full example where we invert the colors of an image if it’s dark mode:
1
2
3
4const img = document.querySelector('#myimage');
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
img.style.filter = "invert(100%)";
}In this example, the
imgvariable represents the image element, and by applying the CSSfilterproperty with theinvertfunction, we invert the colors.
However, we need to handle a potential issue. What if the user changes the mode while using our website? To address this, we can detect the mode change using an event listener:
1 | window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (event) => { |
In the code snippet above, we listen for changes to the preferred color scheme using the change event and determine the mode based on the matches property of the event.
Tags: dark mode, JavaScript, CSS, prefers-color-scheme, image, event listener