Enabling Dark Mode On Websites Based On Surrounding Light

January 4, 2019

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 on twitter, where they changed font weight based on ambient light using variable fonts.

However, they mention further in the thread that they 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! :)

Update: If you're getting an error, something like AmbientLightSensor does not exist on type Window while trying to make this work in Angular, you can fix that by doing following -

You need to extend the existing Window interface to tell it about this new property. So, before your class implementation add this code -

declare global {
    interface Window {
        AmbientLightSensor: any;
    }
}

Then you can add your AmbientLightSensor code in the following way -

    if (window.AmbientLightSensor) {
        const sensor = new window.AmbientLightSensor();
        sensor.onreading = () => console.log(sensor.illuminance);
        sensor.onerror = event => console.log(event.error.name, event.error.message);
        sensor.start();
    }

Reference

Read another post