Created
June 27, 2018 15:12
-
-
Save deanhume/5f341f805b83645f55bda45dbce7fb0e to your computer and use it in GitHub Desktop.
Ambient Light Sensor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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