How to Create Progress Bar using Javascript

interview questions
Progress Bar

In Web Developer Interview, you may get asked to create some interactive components to test your knowledge with latest APIs.

Read: Interview Question to Create TODO App!

How to Answer for web design Tech interview Question.

In this article we will cover Progress Bar Component using vanilla Javascript and then we will redefine it using latest framework as they have built in open source libraries to work with.

It is good to show information and knowledge about open source frameworks as they are cost effective and it has been already tested for browsers and device compatibility.

To answer this coding question you may ask couple of questions like how i should fill progress bar with click event or onload event. Should it be filled 100% once user clicks.

Once you know what exactly your scope of work, you can start writing code. It is always best practice to create Mobile first HTML/CSS responsive layout and then add javascript to it for Event Listener!

So, First we will create progress bar layout using HTML5/CSS3.

HTML5 Code:

<div class="progressbar">
  <div class="activebar" style="font-size:18px;></div>
</div>

CSS3 Code:

.progressbar {
  width: 500px;
  background-color: black;
}

.activebar {
  animation: load 3s normal forwards;
  background-color: orange;
  height: 30px;
  width: 0;
}

Before we jump into Javascript Implementation we can also create progress bar with css3 keyframes! Here is the code.

@keyframes load {
  0% { width: 0; }
  100% { width: 68%; }
}

Checkout this demo.

Now, we will use Javascript to update css dynamically.

let i = 0;
const fillPogressBar = () => {
  if (i == 0) {
    i = 1;
    let elem = document.querySelector(".activebar");
    let width = 1;
    const frame = () => {
      if (width >= 100) {
        clearInterval(id);
        i = 0;
      } else {
        width++;
        elem.style.width = width + "%";
      }
    }
    let id = setInterval(frame, 10);
  }
}
window.onload = fillPogressBar();

Instead of filling progress bar on Window Onload event, we can actually add Click handler.

<button id="clickme" onclick="fillPogressBar()">
  Click Me to Start Progress Bar!
</button>

Here you can checkout the Demo.

There are Few other Libraries like Bootstrap, Material UI have progress bar component ready for you. You can just use it from there and customize it for your need.

One example of Bootstrap:

React Semantic UI also have lots of ready to use options. It is always good idea to show multiple options as it indicates your knowledge for different frameworks and libraries.

In our next article we will create progress bar component in React using state and functional and class components. Stay Tune!