Now you can switch between a "dark mode" and "normal mode" on a website based on the surrounding light! It can really help in curating a better user experience based on the conditions users are viewing your website.
So, here's how you do it-
Adding the short and simple javascript.
if ( 'AmbientLightSensor' in window ) {
const sensor = new AmbientLightSensor();
sensor.onreading = () => {
console.log('illuminance level :', sensor.illuminance);
if(sensor.illuminance < 15) {
document.querySelector('body').classList.add('dark');
}
else {
document.querySelector('body').classList.remove('dark');
}
};
sensor.onerror = (event) => {
console.log(event.error);
};
sensor.start();
}
Then, add specific css for your dark mode under the class you've just set. Like here I am adding and removing the class dark
based on the level of ambient light.
You can play around with the illuminance
value and see what works better in your case.
I also found this cool experiment by @tomlokhorst, where he changed font weight based on ambient light using variable fonts.
However, he mentions further in the thread that he did not use the aforementioned AmbientLightSensor
but it still makes a pretty good use case.
Disclaimer: The browser support for this feature is low.
On chrome it's only available under a flag. Check the caniuse stats for more details. Despite that the future of web is bright or in a dark mode, however you like it! :)
EDIT-
If you're getting an error, something like AmbientLightSensor does not exist on type Window
while trying to make this work in Angular, refer to this comment for a solution.
Reference
- Ambient Light Sensor W3C Spec
- Since I mentioned variable fonts, here is an interesting read on that
Latest comments (28)
I called you at Codepen.io, but you seem not to read the notification. So I came to alert you that it does not work on Google Chrome on Android phone.
Hello Ananya,
Great that you liked the ALS feature on Chrome. We are planning to ship ALS on Chrome by default sometime soon. It would be great to get more inputs
from creative webdev folks. Feel free to ask for more details :)
Riju,
(ALS/sensors -chrome+W3C)
It’s mind-blowing. I never imaged such a thing is possible.
Furthermore such a small amount of code without asking permission. Love it.
Thank you so much for letting me know.
So stoked to see someone writing about this!
The web APIs are growing and I am so ready to see what people build with these!
Great work!
Thanks! Indeed, web APIs are growing and it's exciting!
I read a similar article last year which convinced me that Ambient Light Sensor API is very cool! Check it out!
Very cool! Thanks for sharing :)
Amazing. 🤓
If there is no sensor available then you might also just use the local time. Maybe not for a complete dark mode but for something like a night shift mode. The same way the OSs are doing it.
Implementing this right away! thanks for sharing