DEV Community

Cover image for How to use Battery Status API?
Jatin Sharma
Jatin Sharma

Posted on

How to use Battery Status API?

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

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

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>
Enter fullscreen mode Exit fullscreen mode

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

/* 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;
}
Enter fullscreen mode Exit fullscreen mode

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

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");
  }
});

Enter fullscreen mode Exit fullscreen mode

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

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

Also Read

Top comments (2)

Collapse
 
sintomaticonegativo profile image
Gianluca Tuscano

Interesting, but as far as i know from 2016 this API is deprecated

Collapse
 
j471n profile image
Jatin Sharma

Yeh, You are right it is deprecated, but some browser still supports it.