matt
matt

Reputation: 44303

Animate css progress bar without jumping between updates?

I'm using this on my site …

<progress id='video-progress' min='0' max='100' value=''></progress>

This is the entire styling of the element …

#video-progress {
    -webkit-appearance: none;
    border: none;
    position:fixed;
    bottom:0;
    left:0;
    height:3px;
    width:100%;
    z-index:1;
}

So all it does is move from 0 to 100% screen width on the bottom of the page. The progress bar is updated via Javascript.

However since my video is only 30 seconds long, the single steps of updates are executed as "jumps" for the progress bar. So there is no smooth motion of the bar.

Any idea how I could animate the progress bar or smooth it between the updated steps?

UPDATE:

JavaScript … 

function updateProgressBar() {
    var progressBar = document.getElementById('video-progress');
    var percentage = Math.floor((100 / fmVideo.duration) * fmVideo.currentTime);
    progressBar.value = percentage;
}

Upvotes: 15

Views: 9741

Answers (2)

Marventus
Marventus

Reputation: 874

This works perfectly for me!

function smoothProgress(e) {
    var id = $("#"+e.data.id),
        dur = 5000,
        seq = 100,
        max = parseInt( id.attr("max"), 10),
        chunk = max / dur * seq,
        loop = setInterval(function() {
        if( id.val() < max )
            id.val( id.val() + chunk );
        else
            clearInterval(loop);
        }
    }, seq);
}
$(document).ready(function() {
    $("#launch").on("click", {id: $("progress").attr("id")}, smoothProgress);
});

Of course, you can adjust the dur parameter or retrieve it dynamically based on your video's duration, as well as the seq parameter (the lower, the smoother).

Here is a fiddle for demo.

Upvotes: 2

Weafs.py
Weafs.py

Reputation: 22992

You could animate it by incrementing its value every 15 millisecond using setInterval and stop incrementing if the value is greater than percentage using clearInterval.

This code extracts the current value and increments it until it reaches the percentage value.

Note: percentage is manually set to 70.

var progressBar = document.getElementById('video-progress');

function updateProgressBar() {
  var percentage = 70;
  var curr = progressBar.value;
  var update = setInterval(function() {
    if (curr > percentage) {
      clearInterval(update);
    }
    progressBar.value = curr++;
  }, 15)
}

updateProgressBar();
#video-progress {
  -webkit-appearance: none;
  border: none;
  position: fixed;
  bottom: 0;
  left: 0;
  height: 3px;
  width: 100%;
  z-index: 1;
}
<progress id='video-progress' min='0' max='100' value=''></progress>

Upvotes: 6

Related Questions