I made a program that would list the battery level and charging into a div. My code is below. For some reason, when I run it, it tells me that navigator.getBattery
is not a function. How can I fix this?
function batttick() {
navigator.getBattery().then( a=>{
let m = ""
let c = ""
m = battery.level * 100 + "%"
if(a.charging) {
m+=" ⚡";
c = "green";
}
console.log(c, m);
document.getElementById("batt").innerHTML = m;
document.getElementById("batt").style.color = c;
})
}
batttick()
You had an issue where you were using a variable a
but were referencing battery
. See my edits and working demo:
function batttick() {
navigator.getBattery().then(battery => {
let m = ""
let c = ""
m = battery.level * 100 + "%"
if (battery.charging) {
m += " ⚡";
c = "green";
}
console.log(c, m);
document.getElementById("batt").innerHTML = m;
document.getElementById("batt").style.color = c;
})
}
batttick()
<div id="batt"></div>