By Aurelio De Rosa
Until few years ago when developing a website, we had to rely on several third-party plugins to achieve a lot of tasks. To remember those times, we don’t have to look too far back. Just recall what you used to do when you needed to embed a video or audio in a web page only just a few years ago. Today, the landscape has changed dramatically thanks to HTML5 and related technologies. Nowadays we’ve an API for almost everything, and I suspect that in few years we’ll remove the almost.
One of the most recent APIs I’ve been introduced to is the Ambient Light API. In this article we’ll discuss what it is and what it is useful for.
What is the Ambient Light API
The Ambient Light API defines events that provide information about the ambient light level, as measured by a device’s light sensor
. The data about the luminosity are retrieved using the device’s light detector. This API was initially part of the Sensor API but then split to become an independent API. It isn’t really that new considering that it reached the state of W3C Candidate Recommendation as of 1st October 2013.
The use cases for this API are narrow but still very interesting. The point is to do something based on the quantity of light. But what can we do exactly?
One example might be to change the theme of a website based on the current luminosity of the environment. Let’s say that our website has a blue background with a red color for the text. Now, imagine a user is in a room with the lights turned off, hence very dark. Using the Ambient Light API we can detect the luminosity and set an appropriate theme. In this case, perhaps one having a dark background with a light color for the text. Doing so would avoid causing stress the eyes of our users. Conversely, in a bright environment, for instance if someone is in a park on a sunny day, we can set a light theme. This theme may be one having a light background with a dark color for the text.
Another example might be to adapt the conditions of a game’s environment based on the light. In this case, we may detect decreasing luminosity, like a sunset, and reproduce it in the game (for example a race during the sunset in a racing game).
Some of you may argue that because the first use case deals with style, it should be managed using CSS. I must confess that I agree with you. Not surprisingly, such a proposal already exists and is defined in the level 4 of the media queries specification. Discussing this proposal, called light-level
, is outside the scope of this article. In case you’re interested, you can read more about the light-level
media feature. Before you get too excited about this though, I’ll inform you that at the moment none of the major browsers supports this feature.
Now that we’ve discussed what this API is, let’s see what it has to offer.
Events
The Ambient Light API defines two events that we can listen for to adapt our page to the light conditions. The first event is called devicelight
and provides information about the ambient light levels in terms of lux units.The second event is called lightlevel
and describes the light level as a value being dim, normal, and bright. Both these events are fired on the window
object, so to listen for them we need to attach a handler to it.
An example of how to attach a handler for the devicelight
event is shown below:
window.addEventListener('devicelight', function(event) {
console.log('The current value of light is ' + event.value + ' lux');
});
Now that we know what events this API exposes, we may want to know what browsers support it.
Browser Compatibility
The support for the Ambient Light API is very low at the moment. The only browser that supports the devicelight
event is Firefox, both on desktop and mobile. However, the desktop version support is limited to the Mac OS X, while the implementation for Windows is still in progress. In case you’re interested, you can follow the updates here.
Even worse, the lightlevel
event is not supported by any of the major browsers.
Because this API has been implemented by so few browsers (actually just one, Firefox), it’s important to know how to test for its presence. This is very easy to do by using the same method employed for other APIs as shown below:
if ('ondevicelight' in window) {
// API supported. How much light is there?
} else {
// API not supported :(
}
In the same way, we can test for the support of the lightlevel
event.
Now that we’ve discussed the Ambient Light API in depth, it’s time to see it in action.
Demo
The demo we’ll build perform two main tasks: showing the values returned by the two events of the API and change the theme based on the luminosity.
The markup of our demo is pretty straightforward. We have two span
elements with a message to specify if a given event is not supported. By default both of them are hidden but are shown as needed. We have an unordered list that we’ll use to show the values.
With the markup in place, it’s time to develop the logic. The first thing we need to do is to test the browser to see if it supports the Ambient Light API. As we’ve seen, it’s made of two independent events, so we’ll test them one at a time. If a specific event isn’t supported, we display an appropriate message on the screen using span
elements. If the browser supports an event, we attach a listener to the latter. Inside each of them, we’ll retrieve the value returned (either the number of lux or the string specifying the range) and set it as the text of the appropriate element. In addition, inside the handler of the ondevicelight
event, we test the value to change the theme of the page.
The source of the demo is shown below, but you can also play with it live. In addition, this API is part of my HTML5 API demos repository, a collection of demos that I’ve developed that allows you to play with tens of APIs introduced by HTML5 and its related technologies.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="author" content="Aurelio De Rosa">
<title>Ambient Light API Demo by Aurelio De Rosa</title>
<style>
*
{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body
{
max-width: 500px;
margin: 2em auto;
padding: 0 0.5em;
font-size: 20px;
}
h1
{
text-align: center;
}
.api-support
{
display: block;
}
.hidden
{
display: none;
}
.value
{
font-weight: bold;
}
.author
{
display: block;
margin-top: 1em;
}
.dark-theme
{
background-color: #000000;
color: #FFFFFF;
}
.classic-theme
{
background-color: #DDCBB4;
color: #996666;
}
.light-theme
{
background-color: #FFFFFF;
color: #000000;
}
</style>
</head>
<body>
<h1>Ambient Light API</h1>
<span id="dl-unsupported" class="api-support hidden">devicelight event not supported</span>
<span id="ll-unsupported" class="api-support hidden">lightlevel event not supported</span>
<ul>
<li>
The current light is <span id="dl-value" class="value">null</span> lux.
</li>
<li>
The current state is <span id="ll-value" class="value">null</span>.
</li>
</ul>
<small class="author">
Demo created by <a href="https://www.audero.it">Aurelio De Rosa</a>
(<a href="https://twitter.com/AurelioDeRosa">@AurelioDeRosa</a>)
</small>
<script>
if (!('ondevicelight' in window)) {
document.getElementById('dl-unsupported').classList.remove('hidden');
} else {
var lightValue = document.getElementById('dl-value');
window.addEventListener('devicelight', function(event) {
lightValue.innerHTML = Math.round(event.value);
if (event.value < 50) {
document.body.className = 'dark-theme';
} else if (event.value < 10000) {
document.body.className = 'classic-theme';
} else {
document.body.className = 'light-theme';
}
});
}
if (!('onlightlevel' in window)) {
document.getElementById('ll-unsupported').classList.remove('hidden');
} else {
var lightStateValue = document.getElementById('ll-value');
window.addEventListener('lightlevel', function(event) {
lightStateValue.innerHTML = event.value;
});
}
</script>
</body>
</html>
Conclusion
In this article, we’ve learned what the Ambient Light API is and what it’s good for. We’ve discussed the events provided and how we can use them to adapt the behavior or the style of our web pages based on the values returned. This API is very easy to incorporate in our project, but due to the lack of browser support, this is probably not the time to employ it in our projects. In fact, the support for the Ambient light API is very low with Firefox being the only browser to have implemented it.
In case you want to see the API in action, I suggest you to play with the demo using your smartphone or Mac and Firefox. I hope you enjoyed the article and find it informative.
Hi Aurelio,
I really enjoyed your article. On the past few days I was told to make a demo project for a possible job position they wanted you were creative about the features you could add to the project, the short story is I ended up adding a night /day mode feature on the web app and this reminds me that. Thanks for your article honestly I had not idea about this API.
Hello Felix.
Such a pity you didn’t know about this API, it would have been a good fit for the demo if you turned with the day/night idea. In case you’re interested in more APIs, keep an eye on this repo of mine (https://github.com/AurelioDeRosa/HTML5-API-demos). I’ve more APIs coming soon!
Hello Aurelio,
The ambient light api is now available for chrome (android and Mac) behind a flag.
https://twitter.com/rijubrata/status/558259770097143809
I am going to implement it as css mq on chrome if there is enough developer interest.
Any chance this would work with Cordova apps?