I'm trying to make a button that displays your computer's current battery level. The way it works is, you click a button and in the JavaScript console, it displays your computers current battery level. Instead of putting the level in the console, is there a way to display the level below the anchor tag?
function batlevel() {
navigator.getBattery().then(function(battery) {
var level = battery.level;
console.log(level);
})
};
<a onclick="batlevel()">hi</a>
CodePudding user response:
Consider the following.
function getBatLevel(target) {
var level;
navigator.getBattery().then(function(battery) {
level = (battery.level * 100);
if (target == undefined) {
console.log(level "%");
} else {
target.after(" " level "%");
}
});
};
<a onclick="getBatLevel(this)">Get Level</a>
This makes use of the .after()
call: https://developer.mozilla.org/en-US/docs/Web/API/Element/after
You can wrap it in a Element if you choose.
CodePudding user response:
Pretty straight forward. Get the element you want to append to, create a tag, set innerText and then append
function batlevel() {
navigator.getBattery().then(function(battery) {
var level = battery.level;
var p = document.createElement("p");
p.innerText = level;
document.getElementsByTagName('a')[0].append(p)
console.log(level);
})
};
<a onclick="batlevel()">hi</a>
CodePudding user response:
function batlevel() {
navigator.getBattery().then(function(battery) {
var level = battery.level;
console.log(level);
document.getElementById('levelId').innerHTML = 'this is the level' level;
})
};
<a onclick="batlevel()">hi</a>
<div id="levelId"></div>