Detecting ambient light in JavaScript using the device's sensor is one of those little-known features that, when you discover it, makes you rethink how to customize the user experience in a web application. Thanks to this technology, we can adapt interfaces, change visual styles, or decide what content to show based on the real lighting of the user's environment.
We can detect the level of ambient light obtained by the device's light sensor—meaning a smartphone or tablet—with JavaScript; this way it is possible to configure applications according to the level of light present in the environment; for example, it is possible to add a night mode or a day mode according to the level of light present in the environment; these levels are measured in Lux as you can consult in the official documentation.
Although it is not a widely supported API, it remains an interesting resource to understand how far JavaScript can go when it relies on device sensors, getting closer and closer to functionalities typical of native applications.
Previously we saw how to use Web Workers in JavaScript.
What is the ambient light sensor and what is it for?
The ambient light sensor is a physical component present in many mobile devices and tablets that measures the intensity of light in the environment. This measurement is expressed in lux, a standard unit for quantifying illumination.
In JavaScript, this sensor allows you to:
- Detect if the environment is dark or very bright
- Automatically adjust the user interface
- Activate night or day modes
- Improve readability and visual comfort
Although at first glance it seems like a technology with little practical use, when you start thinking about real applications—such as visual content, multimedia, or interfaces with many light colors—the potential is evident.
Devicelight is a little-known technology in JavaScript that might seem to have no apparent use; although on the other hand, it is one of those technologies that little by little are absorbing features that are present in native apps like in Android or iOS; remember that everything has utility, and we can easily take advantage of this subtle technology.
For example, if we want to present a visual or audiovisual resource and it has many light colors, if there is a low-light environment, which we can obtain with this technology, then we can decide whether to send one resource or another depending on the amount of light.
The configuration and personalization possibilities that a web application can have according to the level of ambient light present are the same offered by the infinity of options we have with JavaScript; the only limit is our imagination.
We can summarize it as: "The returned lux unit ranges between low and high values; dark values are less than 30 lux while very bright ones are 10,000 and above."
DeviceLightEvent API event to detect light variations
We have to apply an event called DeviceLightEvent; this event is triggered when the browser detects variations in the light level.
To detect ambient light in JavaScript, the devicelight event is used, belonging to the sensors API.
This event fires automatically when the browser detects a change in the intensity of light captured by the device's sensor.
Basic operation
- The browser accesses the ambient light sensor
- The devicelight event is triggered
- The event returns a numerical value representing light intensity
- We can react to that value with JavaScript logic
From the event, we can query a value measured in Lux which is what we are interested in checking to detect variations or the current lux level:
Lux "Unit of measurement for illumination according to a luminosity function"
Basic example:
window.addEventListener("devicelight", function (event) {
var lux = event.value; //*** To Do
});In any case, it is worth testing and getting to know this technology with so many possibilities it can offer us and its simplicity of use; let's see a small example that you must remember to test in an updated version of Firefox mobile:
window.addEventListener("devicelight", function(event) {
// Obtain the lighting value in lux
var lux = event.value;
// lux <= 30 indicates a dark or low-light environment
if (lux <= 30) {
document.getElementById('pagestyle').setAttribute('href', 'nightmode.css');
} else {
document.getElementById('pagestyle').setAttribute('href', 'daymode.css');
}
// Update the visual content to display the current lux value
document.getElementById("lux").innerHTML = lux + " lux";
});What are lux and how to interpret light values
The value returned by the ambient light sensor is measured in lux, which is the standard unit for illumination.
According to the Mozilla Foundation:
Low lux values indicate dark environments, while high values represent very brightly lit environments. As a reference, less than 30 lux is a dim environment, and more than 10,000 lux corresponds to very intense lighting.
The Mozilla Foundation says: "It comes returned in the lux unity. The lux value ranges between low and high values, but a good point of reference is that dim values are under 30 lux, whereas really bright ones are 10,000 and over."
In practical terms:
- ≤ 30 lux → Dark environment
- 30 – 1,000 lux → Normal lighting
- > 10,000 lux → Very intense light (outdoors)
When I tested this API, one of the key points was understanding these ranges well so as not to apply abrupt changes to the interface and achieve a natural visual transition.
DeviceLightEvent API example to vary CSS according to luminosity level
A very specific example that presents one of the multiple uses this API can have; the previous experiment consists of changing the light colors of the interface upon detecting low luminosity (dark environment) in the environment through the loading of a different CSS that is activated/deactivated upon detecting certain values in light luminosity.
window.addEventListener("devicelight", function(event) {
var lux = event.value;
document.getElementById("lux").innerHTML = lux + " lux";
});We have a link tag with id=pagestyle where we reference a small style sheet, now then:
Click here to see the example; I recommend testing the example on a device with Firefox OS or in Firefox for Android.
- When the returned lux unit
var lux = event.value;is less than or equal to 30, it is a dark environment and therefore we replace the default style sheet calleddaymode.csswithnightmode.css. - Otherwise (the returned lux unit is greater than 30) we replace
nightmode.csswithdaymode.css.
This small snippet already allows us to:
- Read the sensor value
- Visualize it in real time
- Use it as a base for conditional logic
From here, the possibilities grow rapidly.
Click here to see the example; I recommend testing the example on a device with Firefox OS or in Firefox for Android.
Changing CSS based on ambient light (dark and light mode)
One of the most common uses of the ambient light sensor is to activate a dark or light mode automatically.
This approach seems especially useful to me when you work with interfaces loaded with visual elements, as you can decide which resources to show based on the environment's lighting.
Example: dynamically changing style sheets
window.addEventListener("devicelight", function(event) { var lux = event.value; if (lux <= 30) { // Dark environment
document.getElementById('pagestyle') .setAttribute('href', 'nightmode.css'); } else { // Bright environment
document.getElementById('pagestyle') .setAttribute('href', 'daymode.css'); } });In this case:
- If the environment is dark, we load a CSS with soft colors
- If there is good lighting, we use a light style sheet
This pattern is simple, effective, and very well demonstrates the real value of detecting ambient light with JavaScript.
Real use cases of the ambient light sensor
Even if it's not a mainstream technology, there are scenarios where it makes a lot of sense:
- Visual content adaptation
- If an application shows images or videos with many light colors, you can decide to show alternative versions when there is little ambient light.
- More comfortable interfaces
- Automatically activating a night mode improves the user experience without them having to do anything manually.
- Educational or experimental applications
- This type of API is ideal for projects that explore sensors and environmental behavior.
- As I have personally verified, the true limit of this technology is not JavaScript, but the creativity with which you decide to use it.
Compatibility and limitations of the light sensor in browsers
At the time of writing and updating this content:
- DeviceLightEvent is an obsolete (deprecated) technology that is being removed from browsers; it has been abandoned by almost all major browsers due to privacy concerns (specifically because of the risk of fingerprinting and side-channel attacks to spy on the user).
- It is not supported by most modern browsers.
For this reason:
- It is not recommended for critical production projects.
- It is very interesting for testing, learning, and experimentation.
Even so, knowing this API gives you a broader view of what JavaScript can do when integrated with real hardware.
Is it worth using the ambient light sensor today?
From my point of view, yes, it is worth knowing, even if it is not a mass-use technology.
Not all APIs are meant to solve immediate problems; many serve to:
- Learn
- Experiment
- Anticipate future functionalities
The ambient light sensor is a good example of how JavaScript is absorbing features typical of native applications, and how a website can react to the user's physical environment.
Frequently Asked Questions (FAQs)
- What event is used to detect ambient light in JavaScript?
- The devicelight event is used, which fires when the intensity of light captured by the device's sensor changes.
- In what unit is ambient light measured?
- Light is measured in lux, a standard unit for quantifying illumination.
- Does it work in all browsers?
- No. Support is limited and has been mainly implemented in Firefox, especially on mobile devices.
- Can it be used to activate dark mode?
- Yes, it is one of the most common uses: changing styles or CSS according to the level of ambient light.
AmbientLightSensor
The Ambient Light Sensor API is a more modern interface that allows web applications to access a device's light sensor data (like the sensor that adjusts automatic brightness on a mobile or laptop).
Unlike the old and obsolete DeviceLightEvent that we saw before, it is an API that is part of the Generic Sensor API, which means it is much more robust, secure, and efficient in terms of performance.
Here is an example:
if ('AmbientLightSensor' in window) {
try {
// Initialize the sensor
const sensor = new AmbientLightSensor();
// This event triggers every time a change in light level is detected
sensor.addEventListener('reading', () => {
const lux = sensor.illuminance;
console.log(`Ambient light: ${lux} lux`);
// Logic to toggle between dark and light modes
if (lux < 30) {
document.body.classList.add('dark-mode');
document.body.classList.remove('light-mode');
} else {
document.body.classList.add('light-mode');
document.body.classList.remove('dark-mode');
}
});
// Handle potential sensor errors (e.g., lack of permissions)
sensor.addEventListener('error', event => {
console.error('Sensor error:', event.error.name);
});
// Activate the sensor
sensor.start();
} catch (error) {
console.error('The sensor could not be initialized:', error);
}
} else {
// Fallback if the browser does not support the Generic Sensor API
console.warn('AmbientLightSensor is not supported in this browser');
}CSS:
.dark-mode {
background-color: #121212;
color: #e0e0e0;
}
.light-mode {
background-color: #ffffff;
color: #222222;
}Important points to keep in mind
- Unit: sensor.illuminance returns the value in lux
- Permissions:
- Works only in secure contexts (HTTPS)
- Some browsers require explicit permissions
- Compatibility:
- Limited support (mainly Chrome/Edge on Android)
- Does not work on most desktop browsers
- Status: Experimental API (Web Sensors API)
Conclusion
Detecting ambient light in JavaScript with the device sensor is a simple, powerful functionality full of possibilities. Although its compatibility is limited, it offers a clear way to adapt web interfaces to the user's real environment, improving the experience and opening the door to smarter and more contextual applications.
If you ever need your website to react to something as real as the light surrounding the user, this API deserves, at the very least, a try.
I agree to receive announcements of interest about this Blog.
We can detect the level of ambient light obtained by the device's light sensor with JavaScript; In this way it is possible to configure the applications according to the level of light present in the environment.