Skip to content

Instantly share code, notes, and snippets.

@deanhume
Created June 27, 2018 15:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deanhume/5f341f805b83645f55bda45dbce7fb0e to your computer and use it in GitHub Desktop.
Save deanhume/5f341f805b83645f55bda45dbce7fb0e to your computer and use it in GitHub Desktop.
Ambient Light Sensor
const details = document.getElementById("details");
// Feature detection
if (window.AmbientLightSensor){
try{
const sensor = new AmbientLightSensor();
// Detect changes in the light
sensor.onreading = () => {
details.innerHTML = sensor.illuminance;
// Read the light levels in lux
// < 50 is dark room
if (sensor.illuminance < 50) {
document.body.className = 'darkLight';
} else {
document.body.className = 'brightLight';
}
}
// Has an error occured?
sensor.onerror = event => document.getElementById("details").innerHTML = event.error.message;
sensor.start();
} catch(err) {
details.innerHTML = err.message;
}
} else {
details.innerHTML = 'It looks like your browser doesnt support this feature';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment