Enabling Dark Mode On Websites Based On Surrounding Light

Ananya Neogi - Jan 4 '19 - - Dev Community

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();
}

Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . . . . . . . . . . . . .