DEV Community

Cover image for Real time battery level using javascript
Rajamanickam
Rajamanickam

Posted on • Updated on

Real time battery level using javascript

In this tutorial we will make a real-time battery level indicator using JavaScript.

You will need to use the Navigator.getBattery() method to access the battery information of the device. This method returns a Promise that resolves to a BatteryManager object, which contains information about the battery level, charging status, and other properties.

Here is an example of how you can use the Navigator.getBattery() method to create a real-time battery level indicator:

Image description

This code uses the level property of the BatteryManager object to get the current battery level and then sets the width of the progress bar to match.

The addEventListener() method is used to listen for the levelchange event, which is fired whenever the battery level changes, so the progress bar can be updated in real-time.

Source will be available on : https://github.com/erajamanickam/real-time-battery-level

Live demo of Real time battery level indicator : https://erajamanickam.github.io/real-time-battery-level/

Watch on video : https://www.youtube.com/watch?v=aGtoHum4ruA

Codepen : https://codepen.io/erajamanickam/pen/zYJLZPK

Top comments (2)

Collapse
 
ravavyr profile image
Ravavyr

Neat concept, but it does not appear to work on iphone.
I tried both Safari and Chrome on iphone 13 and it shows the green battery as full with no number [my battery is not full currently]

Collapse
 
vulcanwm profile image
Medea

this is cool!