Automatic Dark/Light Theme Switching Based On The Environment Lighting

Automatic Dark/Light Theme Switching Based On The Environment Lighting

Featured on Hashnode

Hello beautiful people ! In this article I will show you how to automatically switch to dark/light theme based on ambient light levels using Ambient Light Sensor API.

What is Ambient Light Sensor API ?

The Ambient Light Sensor API allows web applications to access the light intensity level measured by the device's light sensor.

Getting Started

Add the following markup in your HTML.

<body>
    <h1>hashnode</h1>
    <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1611902473383/CDyAuTy75.png?auto=compress" alt="logo" />
</body>

Add a few lines of CSS.

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');

body {
  font-family: 'Inter', sans-serif;
  background: linear-gradient(to left, #ffffff 50%, #181818 50%) right;
  background-size: 200%;
  color: #333;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.5s, background-position 0.5s;

.slide {
  color: #fff;
  background-position: left;
}

h1 {
  font-size: 50px;
  margin-right: 30px;
}

img {
  width: 80px;
  transition: transform 0.4s;
}

.spin {
  transform: rotate(180deg);
}

The HTML & CSS above gives the following result.

hashnode-1.png

Automate Dark and Light Theme Switching Using Ambient Light Sensor API

Now it's time to put the magic into action.

By using Ambient Light Sensor API, the dark mode theme automatically turns on when the surroundings are dark and turns off when it is bright.

The browser support is not very good at the moment due to security and privacy concerns with ALS API.

In Chrome you can enable it by going to chrome://flags and enabling Generic Sensor Extra Classes.

Make sure the API is available on your browser first.

if (window.AmbientLightSensor) {
 // Supported
} else {
 // Not Supported
}

Create an instance of Ambient Light Sensor.

const sensor = new window.AmbientLightSensor()

When sensor.start() method is called, it starts reporting brightness changes.

sensor.start()

We can use the sensor events to determine if it is activated, whether it has a new reading, or if it encountered an error.

sensor.addEventListener("activated", () => {})
sensor.addEventListener("reading", () => {})
sensor.addEventListener("error", () => {})

A reading event is fired by the sensor when the reading changes.

The actual reading of the ambient light sensor can be obtained from sensor.illuminance

sensor.addEventListener("reading", () => {
    const illuminance = sensor.illuminance;
})

In simple terms illuminance is a value that indicates the current light level in the surrounding area.

In this table, you can find examples of illumination values under various lighting conditions.

Try experimenting with different illuminance values.

In my case I enabled dark mode when illuminance is < 20 and disabled when > 30.

sensor.addEventListener("reading", () => {
    const illuminance = sensor.illuminance;
    if (illuminance < 20) {
      document.body.classList.add("slide");
      document.querySelector("img").classList.add("spin");
    } else if (illuminance > 30) {
      document.body.classList.remove("slide");
      document.querySelector("img").classList.remove("spin");
    }
})

Final JS Code.

if (window.AmbientLightSensor) {
  const sensor = new window.AmbientLightSensor();
  sensor.start();
  sensor.addEventListener("reading", () => {
    const illuminance = sensor.illuminance;
    if (illuminance < 20) {
      document.body.classList.add("slide");
      document.querySelector("img").classList.add("spin");
    } else if (illuminance > 30) {
      document.body.classList.remove("slide");
      document.querySelector("img").classList.remove("spin");
    }
  });
} else {
    alert("Ambient Light Sensor API is not supported !")
}

With this, the dark mode will automatically be enabled when the surrounding area is dark and disabled when it's bright.

hashnode-final-compress.gif

Privacy and Security Concerns with Ambient Light Sensor API

w3.org/TR/ambient-light/#security-and-privacy

blog.lukaszolejnik.com/stealing-sensitive-b..

Thanks for reading. Happy Coding.