W3cubDocs

/Web APIs

BatteryManager: levelchange event

The levelchange event of the Battery Status API is fired when the battery level property is updated.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

js

addEventListener("levelchange", (event) => { })

onlevelchange = (event) => { }

Event type

A generic Event.

Example

HTML

html

<div id="level">(battery level unknown)</div>
<div id="stateBattery">(charging state unknown)</div>

JavaScript

js

navigator.getBattery().then((battery) => {
  battery.onlevelchange = () => {
    document.querySelector("#level").textContent = battery.level;

    if (battery.charging) {
      document.querySelector("#stateBattery").textContent = `Charging time: ${
        battery.chargingTime / 60
      }`;
    } else {
      document.querySelector(
        "#stateBattery",
      ).textContent = `Discharging time: ${battery.dischargingTime / 60}`;
    }
  };
});

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
levelchange_event 38 79 43–52 No 25 No 38 38 43–52 25 No 3.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/BatteryManager/levelchange_event