Created
January 2, 2017 22:12
-
-
Save vrcosta/6b3ae5c999633a4010db430b6f4d7f7d to your computer and use it in GitHub Desktop.
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
// Check the browser capabilities | |
if ('getBattery' in navigator) { | |
navigator.getBattery().then(initBatteryListeners); | |
} else { | |
document.getElementById('content').innerHTML = 'Your browser doesn\'t support the Battery API. Try Chrome or Firefox.'; | |
} | |
// Callback when getting the battery | |
function initBatteryListeners(battery) { | |
updateInterface(battery); | |
// Install listeners | |
battery.addEventListener('levelchange', updateInterface.bind(null, battery)); | |
battery.addEventListener('chargingtimechange', updateInterface.bind(null, battery)); | |
battery.addEventListener('dischargingtimechange', updateInterface.bind(null, battery)); | |
battery.addEventListener('chargingchange', updateInterface.bind(null, battery)); | |
} | |
function updateInterface(battery) { | |
// Battery percentage | |
document.getElementById('battery-percentage').innerHTML = (battery.level * 100) + '%'; | |
// Charging time | |
document.getElementById('charging-time').innerHTML = battery.chargingTime + ' seconds'; | |
// Discharging time | |
document.getElementById('discharging-time').innerHTML = battery.dischargingTime + ' seconds'; | |
// Charging status | |
document.getElementById('charging-status').innerHTML = battery.charging ? 'Yes' : 'No'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment