How to use Battery Status API?
Tags: javascript, webdev, beginners, tutorial
Published: 2021-12-06 03:44:50

In this article, we are gonna build a Battery Informer which will display the battery status and the other information along with it such as the charging status, charging level and the discharging time.  Let's first look at what are we building -

![preview](https://i.imgur.com/vG6yTvB.gif)

Now you know how it will look like, So let's look at the code now  -

### HTML

```html
<div class="battery">
  <div class="main_container">
    <!--  charging information  -->
    <div class="charging_info">
      <p class="battery_level"></p>
      <img class="charging_icon" src="https://i.imgur.com/xy0IMAM.png" alt="charging" />
    </div>
    <!--  Charging bar  -->
    <div class="charging_bar"></div>
    <!--  Charging other info  -->
    <div class="other_info">
      <p>Discharging : <span class="discharging_time"></span></p>
    </div>
  </div>
  <div class="right_bar"></div>
</div>
</div>
```


In the HTML code, the `battery` class is the main container and it has three different section 

- `charging_info` :  it shows the battery level and the charging icon
- `charging_bar` : it is the bar to represent the battery level
- `other_info` : it shows the `discharging_time` 


Now let's look at the CSS -

### CSS

```css
/* Battery main Container */
.battery {
  display: flex;
  align-items: center;
}

/* Battery main Container */
.main_container {
  position: relative;
  background: #fff;
  width: 300px;
  height: 150px;
  padding: 4px;
  border-radius: 15px;
}
.right_bar {
  width: 10px;
  height: 75px;
  border-radius: 15px;
  background: white;
  margin-left: 1px;
}

/* main charging bar  */
.main_container > .charging_bar {
  position: relative;
  background: limegreen;
  border-radius: 15px;
  width: 0;
  height: 100%;
  z-index: 9;
  animation: animate 2s linear;
}

/* the charging animation from the left */
@keyframes animate {
  0% {
    width: 0;
  }
}

/* Charging information  such as battery % and charging Icon */
.main_container > .charging_info {
  position: absolute;
  content: "";
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  font-size: 60px;
  width: 100%;
}

/* Charging Icon */
.charging_info > img {
  width: 35%;
  display: none;
}

/* Other information such as discharging time */
.other_info {
  position: absolute;
  inset: 12px;
  z-index: 10;
  display: none;
}
```

Now the main part is the javascript in order to run this properly.

### JS

```js
// All the containers we need to update the battery information
const chargingIcon = document.querySelector(".charging_icon");
const batteryLevel = document.querySelector(".battery_level");
const chargingBar = document.querySelector(".charging_bar");
const dischargingTime = document.querySelector(".discharging_time");
const otherInfo = document.querySelector(".other_info");

// Getting battery it returns a propmise
navigator.getBattery().then((battery) => {
  /* Update all the battery information which is a combination of multiple functions */
  function updateAllBatteryInfo() {
    updateChargeInfo();
    updateLevelInfo();
    updateDischargingInfo();
  }

  //   Running as the promise returns battery
  updateAllBatteryInfo();

  //  Event Listener, when the charging status changes
  //  it checks that does your device is plugged in or not
  battery.addEventListener("chargingchange", function () {
    updateAllBatteryInfo();
  });

  //  Event Listener, when the Battery Level Changes
  battery.addEventListener("levelchange", function () {
    updateAllBatteryInfo();
  });

  //  Event Listener, when the discharging Time Change
  //  it checks that does your device is plugged in or not
  battery.addEventListener("dischargingtimechange", function () {
    updateAllBatteryInfo();
  });

  //   Updating the battery Level container and the charging bar width
  function updateLevelInfo() {
    batteryLevel.textContent = `${parseInt(battery.level * 100)}%`;
    chargingBar.style.width = `${parseInt(battery.level * 100)}%`;
  }

  function updateChargeInfo() {
    /*
      if the device is plugged in 
          - changing the Animation Iteration Count to infinite
          - showing the charging Icon
          - Hiding the other information
      else 
          - changing the Animation Iteration Count to initial
          - hiding the charging Icon
          - showing the other information
    */

    battery.charging
      ? ((chargingBar.style.animationIterationCount = "infinite"),
        (chargingIcon.style.display = "inline-flex"),
        (otherInfo.style.display = "none"))
      : ((chargingIcon.style.display = "none"),
        (otherInfo.style.display = "inline-flex"),
        (chargingBar.style.animationIterationCount = "initial"));
  }

  //   updating the Discharging Information
  function updateDischargingInfo() {
    const dischargeTime = parseInt(battery.dischargingTime / 60) ? true : false;
    dischargeTime
      ? ((dischargingTime.textContent = `${parseInt(
          battery.dischargingTime / 60
        )} minutes`),
        (otherInfo.style.display = "flex"))
      : (otherInfo.style.display = "none");
  }
});

```

**Note -** `dischargeTime` will not show if it is null/infinity, and in mobile devices it mostly infinity so to view that in action you should use laptop/desktop.


Codepen - 

{% codepen  https://codepen.io/j471n/pen/PoJYLXg  %}

[![codepen](https://imgur.com/MNtTdVp.png)](https://codepen.io/j471n/pen/PoJYLXg)



### Conclusion

This shows the battery information of your device. you can use this on your website to show the battery status of the users

> You can now extend your support by buying me a Coffee.😊👇
[![buymecoffee](https://imgur.com/2QWo3cm.png)](https://www.buymeacoffee.com/j471n)

### Also Read
- [Curved Timeline in CSS](https://dev.to/j471n/curved-css-timeline-5ab3)
- [How to use Web Storage API?](https://dev.to/j471n/how-to-use-web-storage-api-3o28)
- [Typing Effect by using CSS](https://dev.to/j471n/typing-effect-by-using-css-50p)