Categories
JavaScript Answers

How to Make a Progress Bar with HTML and JavaScript?

Spread the love

Sometimes, we want to make a progress bar with HTML and JavaScript.

In this article, we’ll look at how to make a progress bar with HTML and JavaScript.

Make a Progress Bar with HTML and JavaScript

To make a progress bar with HTML and JavaScript, we can set the width of a div to be a percentage of its containing div.

For instance, we write:

<div id="container" style="width: 100%; height: 5px; border: 1px solid black;">
  <div id="progress-bar" style="width:10%; background-color: green; height:5px;"></div>
</div>

to add the outer and inner divs for the progress bar.

We set the background color of the inner div to make the progress bar show.

Then we write:

let width = 0;
const progressBar = document.getElementById('progress-bar')
window.onload = (e) => {
  setInterval(() => {
    width = width >= 100 ? 0 : width + 5;
    progressBar.style.width = width + '%';
  }, 200);
}

We define the width variable to set the width of the inner div.

Then we select the progress bar’s inner div with document.getElementById.

Next, we set the window.onload property to a function that updates the width of the inner div when the page loads.

To do this, we call setInterval with a callback that sets the width.

If width is bigger than or equal to 100, we reset it to 0.

Otherwise, we add 5 to width and assign it to width.

Next, we set the style.width property of the inner div to width percent to update the bar’s length as a percentage of the width of the outer div.

We pass in 200 as the 2nd argument of setInterval to update the width every 200 milliseconds.

Therefore, now we should see the progress bar being filled and emptied periodically.

Conclusion

To make a progress bar with HTML and JavaScript, we can set the width of a div to be a percentage of its containing div.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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