Skip to content

Battery Status API experiment

Screenshot of JavaScript battery API experiment
Battery UI element

The JavaScript Battery Status API offers some interesting additional functionality that we can leverage for UI elements. Browser support is getting better—at the time of writing (Feb, 2017), Chrome, FireFox and Opera are good to go, but leaves glaring omissions of Safari/iOS.

This little experiment creates a simple battery UI element, with its background an indicator of battery percentage remaining (plus percentage text): CodePen Experiment

The API provides a bunch of events we can hook into:

  • chargingchange – is the battery charging?
  • levelchangepercentage of battery remaining
  • chargingtimechangeamount of time until battery is charged (estimate)
  • dischargingtimechangeamount of time until batter is discharged (estimate)

All we need to do is check that we have support for the API and off we go:

navigator.getBattery().then(function(battery) { ... });

Once we know we have battery API support, we can go ahead and add some listeners for the new events and update our UI as we need. Note, we don’t use any libraries here, this is raw JavaScript:

const $batteryPercentage = document.querySelector(".js-guage");
const $batteryPercentageDisplay = document.querySelector(".js-percentDisplay");
const $batteryStatusDisplay = document.querySelector(".js-statusDisplay");

navigator.getBattery().then(function(battery) {
 function initBattery(){
 battery.addEventListener('chargingchange', function(){
 battery.addEventListener('levelchange', function(){
 function updateChargeInfo(){
   let _batteryChargeStatus = battery.charging ? "Battery Charging" : "Battery Draining"; 
   $batteryStatusDisplay.innerHTML = _batteryChargeStatus;

 function updateLevelInfo(){
   let _batteryLevel = Math.round(battery.level * 100) + "%";
   $ = _batteryLevel;
   $batteryPercentageDisplay.innerHTML = _batteryLevel;


What could we use the Battery Status API for?

  • Intensive or full-screen scripts could warn the user if the battery was low before beginning, such as Canvas, WebGL or media handling.
  • Coupled with up-coming CSS selector prefers-reduced-motion we could trigger low-animation CSS when the battery is getting tight.

Details of support for the Battery Status API can be found on Can I Use.

Leave a Reply

Your email address will not be published. Required fields are marked *