Update a Progress Bar with JavaScript

The HTML <progress> element represents the completion of a task. JavaScript can read its current value, compare it with max, and update it when a button is clicked.

50% 50%

See also the HTML5 progress tag tutorial and the button click / show-hide layer example used by the original page.

Table of Contents

Displaying the Progress Bar Top ↑

<progress value="50" max="100" id="p1">50%</progress>

Link the Value to a Button Click Top ↑

The original page used a button labelled “Increse.” The facility is retained with the spelling corrected to “Increase.” The click is registered with addEventListener() rather than inline JavaScript.

<button type="button" id="increase-progress">Increase</button>

Update the Progress Value Top ↑

const progress=document.getElementById('p1');
const button=document.getElementById('increase-progress');
const status=document.getElementById('progress-status');

button.addEventListener('click',()=>{
  progress.value=Math.min(progress.max, progress.value + 10);
  status.textContent=`${progress.value}%`;
  if (progress.value === progress.max) {
    status.textContent='100% - end of the process';
  }
});

The call to Math.min() prevents the value from being pushed above the element's maximum. The original exercise suggested adding a message at the end of the process; the live example now demonstrates that while keeping the same Increase control.

Complete Working Source Top ↑

<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Progress bar</title></head><body>
<progress value="50" max="100" id="p1">50%</progress>
<button type="button" id="increase-progress">Increase</button>
<span id="progress-status" aria-live="polite">50%</span>
<script>const progress=document.getElementById('p1');
const button=document.getElementById('increase-progress');
const status=document.getElementById('progress-status');

button.addEventListener('click',()=>{
  progress.value=Math.min(progress.max, progress.value + 10);
  status.textContent=`${progress.value}%`;
  if (progress.value === progress.max) {
    status.textContent='100% - end of the process';
  }
});</script></body></html>

← Event Handling onMouseOver and onMouseOut →




Subscribe to our YouTube Channel here



plus2net.com







23-02-2020

Thanks a lot for the code. It worked for me.

23-02-2020

Thanks a lot for the code. It worked for me.



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer