DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Access Battery Status through Javascript

How to Access Battery Status through Javascript

Jos Dirksen user avatar by
Jos Dirksen
·
Jun. 11, 12 · Interview
Like (0)
Save
Tweet
Share
10.72K Views

Join the DZone community and get the full member experience.

Join For Free

the html5 specification is maturing and slowly apis surface that allow you to access more information from the device the browser is running on. one of the latest submissions is the " battery status api ". as the name implies the api allows you to access the battery status through javascript. so you could use this api to disable heavy animations on your web page, warn the user to sync its data, or proactively store the data in local storage. if you want to test this for yourself you can find a working example here . note that the "battery time left" property, at least for me, isn't available when i open the page. it updates after a couple of minutes.

i tested this api with the latest betas of mozilla. and it doesn't work yet on mac (does work on ios, android and windows). i also didn't get a good result for the charging time, but discharging and level worked nicely. for this small example we'll just display information from the api in a simple webpage, like this (screenshot from my tablet):

screenshot_2012-06-08-12-20-53.png

we'll look at the following in this article:

  • how to use the battery api
  • create a couple of text fields to show information from the api
  • create a battery image that shows how much power we have left
  • use event listeners to update the information

lets start with a quick look at the api

how to use the battery api

using the api is very simple, it has only a couple of properties you can access (from the spec):

[nointerfaceobject]
interface batterymanager : eventtarget {
    readonly attribute boolean   charging;
    readonly attribute double    chargingtime;
    readonly attribute double    dischargingtime;
    readonly attribute double    level;
};

the charging property indicates whether we're connected to a charger, chargingtime returns the amount of time it will take to completely charge the device, the dischargingtime returns the time it will take to approximately run out of power, and the level shows a percentage of how much power you've got left. very straightforward.

besides these properties the api also defines a couple of callbacks.

    [treatnoncallableasnull]
             attribute function? onchargingchange;
    [treatnoncallableasnull]
             attribute function? onchargingtimechange;
    [treatnoncallableasnull]
             attribute function? ondischargingtimechange;
    [treatnoncallableasnull]
             attribute function? onlevelchange;

you can register functions for these callbacks that will be called whenever one of the properties changes.

create a couple of text fields to show information from the api

lets beging with a couple of simple text fields that show information on the battery. we use the following html:

<div id="box">
    <div id="battery"></div>
    <div id="text">
        <span style="display: block;margin-bottom:15px;font-size: xx-large;"><strong>battery
            specifications</strong></span>
        <span style="display: block" id="level">battery level: unknown</span>
        <span style="display: block" id="status">charging status: unknown</span>
        <span style="display: block" id="charged">battery charged: unknown</span>
    </div>
</div>

and to make sure they have the correct battery value, we fill these with the following javascript:

    // get the battery information
    var battery = navigator.mozbattery;
 
    // get the battery information to be displayed
    $('#level').text("battery level: " + math.round(battery.level * 100) + "%");
    $('#status').text("charging status: " + ((battery.charging) ? "true" : "false"));
    if (battery.charging) {
        $('#charged').text("battery time to charge: " + battery.chargingtime);
    } else {
        $('#charged').text("battery time left: " + (math.round(battery.dischargingtime / 60)) + " minutes");
    }

as you can see in the code, couldn't be much simpler. we also show an image that reflects the level.

create a battery image that shows how much power we have left

i won't go into the details since that isn't that interesting. if you want to see the details look at the source code from the example . for this example i created a simple battery object (based on example from nokia) and with an updatebattery call i can set how full the battery is. to initialize this, use the following:

  var b = new battery("assets/bat_empty.png", "assets/bat_full.png", 96, 168);
    $("#battery").append(b.domelement);
    b.updatebattery(battery.level * 100);

use event listeners to update the information

and finally we add a couple of event listeners that are called whenever one of the properties of the battery changes:

   // when the loader is connected
    battery.addeventlistener("chargingchange", function (e) {
        $('#status').text("charging status: " + ((battery.charging) ? "true" : "false"));
    }, false);
 
    // when charging time changes update the time to charge / time left
    battery.addeventlistener("chargingtimechange", function (e) {
        if (battery.charging) {
            $('#charged').text("battery time to charge: " + battery.chargingtime);
        } else {
            $('#charged').text("battery time left: " + (math.round(battery.dischargingtime / 60)) + " minutes");
        }
 
    }, false);
 
    // when dischargingtime changes update the time to charge / time left
    battery.addeventlistener("dischargingtimechange", function (e) {
        if (battery.charging) {
            $('#charged').text("battery time to charge: " + (math.round(battery.dischargingtime / 60)) + " minutes");
        } else {
            $('#charged').text("battery time left: " + (math.round(battery.dischargingtime / 60)) + " minutes");
        }
    }, false);
 
    // listener that is notified when the level changes
    battery.addeventlistener("levelchange", function (e) {
        $('#level').text("battery level: " + math.round(battery.level * 100) + "%");
        b.updatebattery(100 * battery.level)
    }, false);

easy isn't it? the really good thing about this, is that this works across devices. on my mobile phone it looks like this:

2012-06-08_11-35-31.jpg

and on windows (running in a vm) it shows me this:

windows 7 - ultimate [running].png

JavaScript

Published at DZone with permission of Jos Dirksen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Fargate vs. Lambda: The Battle of the Future

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: