Billy Logan
Billy Logan

Reputation: 2520

How to increment value on progress-bar?

I have a progress bar which is supposed to be filled up from 0% to 100% withing 3 seconds by a click.

Codepen example

<progress class="progress is-large is-info" max="100" value="10"></progress>
</br>
<button onclick="move()">Click Me</button>

Since there is no document.getElementByValue how could I increment value attribute in a loop to get it done?

Upvotes: 1

Views: 8749

Answers (3)

Pugazh
Pugazh

Reputation: 9561

Add the attribute id to your progress bar and access the element by document.getElementById. Also added the loop to show the progress.

Updated CodePen.

Check the example below:

var progress = document.getElementById("progressbar");

function move() {
  var a = setInterval(function() {
    progress.value = progress.value + 1;

    if (progress.value == 100) {
      clearInterval(a);
    }
  }, 25);
}
.progress.is-large {
  height: 40px;
}
<progress id="progressbar" class="progress is-large is-info" max="100" value="10"></progress>
</br>
<button onclick="move()">Click Me</button>

Upvotes: 4

TheThirdMan
TheThirdMan

Reputation: 1522

Here's an approach that is different from your original attempt, however has a few advantages compared to looping +1s:

  • JS is only used to trigger the animation, however animating is entirely handled by the browser - this results in a very smooth animation while needing much less processing power (though that last point is likely irrelevant for most devices, I still prefer it this way)
  • it requires almost no code and incorporates style-ability, which you likely want anyway
  • it scales to the width property of it's parent in a very flexible manner.
  • if you're not looking for a linear progression, you can easily use a different timing function by exchanging a single word

The downside is that it requires CSS3.

#progress-bar-container {
  background-color: #ddd;
  width: 300px;
}
#progress-bar {
  background-color: #08f;
  height: 20px;
  transition: width 3s linear;
  width: 0%;
}
#progress-bar.full {
  width: 100%;
}
<div id="progress-bar-container">
  <div id="progress-bar"></div>
</div>
<button onclick="document.getElementById('progress-bar').className += ' full'">Click Me</button>

Upvotes: 3

Alex Harris
Alex Harris

Reputation: 6392

Adding an id to the progressbar allows to use document.getElementById. After that all that needs to happen is set an interval and increment progress.value. Ids are ideal for this situation as they are unique identifiers for a specific element on the page.

http://codepen.io/chasenyc/pen/grWrKR

function move() {
  var progress = document.getElementById("progressbar");
  var width = 1;
  var id = setInterval(frame, 10);

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      progress.value = width
    }
  }
}

Upvotes: 3

Related Questions