How to use Battery Status API?

Dec 5, 2021
4 min read
738 words

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

preview

Deprecated

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible. Be aware that this feature may cease to work at any time.

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

HTML

index.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>

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

styles.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.

Javascript

script.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.

Wrapping up

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

Jatin's Newsletter

I write monthly Tech, Web Development and chrome extension that will improve your productivity. Trust me, I won't spam you.

Share on Social Media: