-4

I'm trying to build a vanilla JavaScript progress bar.

<div id="progress-bar" style="width:10%;">

Style ranges from width:0% to width:100% in 10 seconds.

I'm looking for a pure JavaScript solution.

Here's a link to my fiddle - http://fiddle.jshell.net/5j6gf/

halfer
  • 19,824
  • 17
  • 99
  • 186
Mo.
  • 26,306
  • 36
  • 159
  • 225
  • @WhiteRabbit: thanks for wanting to edit questions here. However you added five new errors into the question, so I wonder if you might be best contributing in other ways. The community is keen that contributors who make edits are thoroughly versed in technical writing in English. – halfer May 24 '20 at 20:43

3 Answers3

4

Here it is in jsfiddle: http://fiddle.jshell.net/5j6gf/1/

The answer of how to animate in javascript was from here: https://stackoverflow.com/a/11213374/1524085

function animate(elem,style,unit,from,to,time) {
    if( !elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);
            elem.style[style] = (from+step*(to-from))+unit;
            if( step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}

animate(
    document.getElementById('progress-bar'),
    "width","%",0,100,1000
);
Community
  • 1
  • 1
Pedro Estrada
  • 2,384
  • 2
  • 16
  • 24
2

You should consider using a CSS transition instead:

#progress-bar {
  width: 0%;
  -moz-transition: width 10s linear;
  -webkit-transition: width 10s linear;
  transition: width 10s linear;
}

Then

document.getElementById("progress-bar").style.width = "100%";
Andrew
  • 4,145
  • 2
  • 37
  • 42
1

Anything that's possible in jQuery is possible with pure JavaScript. Either fix your question or find how it is done in jQuery and try to rewrite it in JS.

You can use setTimeout or setInterval to increase the width percentage in time. You'll also need to make each increase as smooth as possible by increasing the width by one pixel until you get to the desired width.

There are millions of ways to do it, find one that works for you.

Shomz
  • 37,421
  • 4
  • 57
  • 85