Native HTML 5 Progressibar Animation

Asked

Viewed 522 times

3

How to animate the Progressbar below using Javascript?

<progress max="100" id="myBar" value="0" class="progressBar"></progress>

2 answers

3

You can use setInterval to increase the value of the bar. See the example below:

<progress max="100" id="myBar" value="0" class="progressBar"></progress>


<script>
function move(addthis) 
{
  var elem = document.getElementById("myBar");  
  var loaded = document.getElementById("myBar").value;
  var newvalue = loaded + addthis;
  if(newvalue>100){ newvalue=100; }
  
  var progressvalue = loaded;

  var id = setInterval(function(){ frame(newvalue); }, 10);
  
  function frame(newvalue) 
  {
    if (progressvalue >= newvalue) 
    {
      clearInterval(id);
    } 
    else 
    {
      progressvalue++; 
      document.getElementById("myBar").value = progressvalue;
    }
  }
}

function zero()
{
      document.getElementById("myBar").value = 0;
}
</script>

<br><br>
Teste de carregamento:<br><br>
<input type="button" onclick="move(10)" value="+10%">
<input type="button" onclick="move(25)" value="+25%">
<input type="button" onclick="move(50)" value="+50%"><br><br>
<input type="button" onclick="zero()" value="Recarregar">

3


Simple. Just increment the attribute value of the element.

Functional example

document.getElementById('bt-iniciar').addEventListener('click', iniciarProgressBar);

function iniciarProgressBar(){
    var bar = document.getElementById("myBar");  
    bar.value = 0;
    adicionarDezPorcento();
}

function adicionarDezPorcento() {
  var bar = document.getElementById("myBar");
  bar.value += 5;
  
  if(bar.value == 30) { 
    // aos 30%, esperar 3 segundos
    setTimeout(adicionarDezPorcento, 3000);            
  }
  else if(bar.value < 100) {
    setTimeout(adicionarDezPorcento, 100);
  }
};
<progress id="myBar" max="100" value="0"></progress>

<br>

<button id="bt-iniciar">Iniciar</button>

  • It worked... You would know how to for example 30% progress give a short pause to simulate a request?

  • I liked it, it looked like mine. The difference was only the use of setTimeout and setInterval.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.