Created
December 20, 2023 12:02
-
-
Save shahriarshafin/a15d384e2c9fd87ef7b341aa5ae7dc65 to your computer and use it in GitHub Desktop.
Get Real-Time Battery Information with JavaScript
This file contains 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Real-Time Battery Information</title> | |
</head> | |
<body> | |
<h1>Real-Time Battery Information with JavaScript</h1> | |
<div> | |
<p id="batteryLevel">Battery Level: </p> | |
<p id="chargingStatus">Charging: </p> | |
<p id="chargingTime">Time until charged: </p> | |
<p id="dischargingTime">Time until discharged: </p> | |
</div> | |
<script> | |
// Function to update battery information | |
const updateBatteryInfo = () => { | |
// Access the battery information | |
navigator.getBattery().then((battery) => { | |
// Update the HTML elements with battery information | |
document.getElementById('batteryLevel').textContent = `🔋 Battery Level: ${battery.level * 100}%`; | |
document.getElementById('chargingStatus').textContent = `⚡ Charging: ${battery.charging ? 'Yes' : 'No'}`; | |
document.getElementById('chargingTime').textContent = `⏳ Time until charged: ${battery.chargingTime} seconds`; | |
document.getElementById('dischargingTime').textContent = `⏰ Time until discharged: ${battery.dischargingTime} seconds`; | |
// Schedule the next update after a delay (e.g., 1000 milliseconds) | |
setTimeout(updateBatteryInfo, 1000); | |
}); | |
}; | |
// Initial update | |
updateBatteryInfo(); | |
// React to dynamic changes in battery level and charging state | |
document.addEventListener('batteryStatusChange', updateBatteryInfo); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment