
Recently, there are more and more mobile devices that not only determine the illumination around, but also appropriately change the information displayed on the screen to a more convenient and readable form.
Now this opportunity is slowly being moved to the engines of mobile browsers.
')
The article will consider an example of how a web-page reacts in the browser to ambient light.
Ambient Light Events API
To implement the page's response to light, we will use
Ambient Light Events . This is part of the HTML5
Device APIs that allows you to interact with device services. Ambient Light Events give access to the light sensor using JavaScript.
Light events
The browser raises a DeviceLight event when the sensor detects a change in light level. We will catch him. In the event, the browser transmits the light level transmitted from the sensor.
window.addEventListener('devicelight', function(event) { console.log(event.value + 'lux'); });
Now, when the illumination changes, information about the current level will get into the console.
Learning page to respond to light
To demonstrate the possibilities, we will use three styles of the page, which will be replaced with the necessary one depending on the light intensity:
- with medium illumination - gray background, dark text (standard page display, with no illumination information)
- in high light conditions - white background, dark text
- with low light - dark background, light text
We write the necessary JavaScript code:
window.addEventListener('devicelight', function(e) { var lux = e.value; if(lux < 50) { document.body.className = 'dark'; } if(lux >= 50 && lux <= 300) { document.body.className = 'normal'; } if(lux > 300) { document.body.className = 'bright'; } });
And the corresponding styles for the page:
body, body.normal { background-color: #ddd; color: #111; } body.dark{ background-color: #444; color: #fff; } body.bright { background-color: #fff; color: #333; }
View
DEMO
At the moment, alas, this feature is supported only in Firefox 22+, there should also be a light sensor on the device.
Testing the page was conducted in Firefox on devices Lenovo P780, Nexus 5, Nexus 7.
The page behaves a little differently on these devices, apparently due to the different sensitivity of the sensors.
W3C promised to add definitions of light in
CSS Media Queries 4 via the luminosity parameter, i.e. The above example would look like this:
@media screen and (luminosity: normal) { body {background-color: #ddd; color: #111;} } @media screen and (luminosity: dim) { body {background-color: #444; color: #fff;} } @media screen and (luminosity: washed) { body {background-color: #fff; color: #333;} }
But at the moment the document is still at the draft stage. We will wait for the official announcement of support for this feature.
UPD : At the request of the user,
ange007 added a
trackbar to the page, for easy viewing of the example without a supported device. Also added a QR code for quick viewing on mobile devices.