<p>Define the elements used to display the battery status information on the screen:</p>
<pre class="prettyprint">
<div>charging: <span id="charging"></span></div>
-<div>chargingTime: <span id="chargingTime"></span></div>
-<div>dischargingTime: <span id="dischargingTime"></span></div>
<div>level: <span id="level"></span></div>
</pre>
</li>
document.querySelector('#charging').textContent =
battery.charging ? 'charging' : 'not charging';
- /* Battery charging time: seconds (for example, 3600) or Infinity */
- document.querySelector('#chargingTime').textContent =
- battery.chargingTime / 60;
-
- /* Battery life: seconds (for example, 3600) or Infinity */
- document.querySelector('#dischargingTime').textContent =
- battery.dischargingTime / 60;
-
/* Battery.level: between 0 and 1 (for example, 0.50) */
document.querySelector('#level').textContent =
Math.floor(battery.level * 100) + '%';
/* Detects changes in the battery charging status */
battery.addEventListener('chargingchange', getBatteryState);
- /* Detects changes in the battery charging time */
- battery.addEventListener('chargingtimechange', getBatteryState);
- /* Detects changes in the battery discharging time */
- battery.addEventListener('dischargingtimechange', getBatteryState);
/* Detects changes in the battery level */
battery.addEventListener('levelchange', getBatteryState);
</script>
var message = "";
var charging = battery.charging;
- var chargingTime = getTimeFormat(battery.chargingTime);
- var dischargingTime = getTimeFormat(battery.dischargingTime);
var level = Math.floor(battery.level * 100);
if (charging == false && level < 100)
{
/* Not charging */
- message = dischargingTime.hour + ":" + dischargingTime.minute +
- " remained.";
- if (battery.dischargingTime == "Infinity")
- {
- message = "";
- }
- }
- else if (charging && level < 100)
- {
- /* Charging */
- message = "Charging is complete after "
- + chargingTime.hour + ":" + chargingTime.minute;
- if (battery.chargingTime == "Infinity")
- {
- message = "";
- }
}
else if (level == 100)
{
document.querySelector('#progress').value = level;
document.querySelector('#message').textContent = message;
}
-
- /* Time is received in seconds, converted to hours and minutes, and returned */
- function getTimeFormat(time)
- {
- /* Time parameter is second */
- var tempMinute = time / 60;
-
- var hour = parseInt(tempMinute / 60, 10);
- var minute = parseInt(tempMinute % 60, 10);
- minute = minute < 10 ? "0" + minute : minute;
-
- return {"hour": hour, "minute": minute};
- }
</script>
</pre>
-<p>If the battery is not charging, a message is displayed telling you to charge the battery. You can see how much time remains until the battery runs out. In the battery is charging, you can see the time left until it is fully charged.</p>
+<p>If the battery is not charging, a message is displayed telling you to charge the battery.</p>
<p>
You can use a progress bar to display the battery charging level.
</p>