The problem is that you are using element content for two effects:
Save the current value ( valorInicial
).
Save the desired final value.
When you get to the innerHTML change line, it eventually changes the final value per drag.
So let's start by trying to make the counter increment, without waiting for it to stop eventually.
HTML:
<li class="marcacao" onMouseOver="aumenta('html')">HTML5 e CSS3
<div id="html" class="nivel">100</div>
</li>
JavaScript:
function aumenta(id){
var valorAtual = 0;
setInterval(function(){
var elemento = document.getElementById(id);//pega a div com o número
elemento.innerHTML = valorAtual++;
},20)
}
Let's now set a fixed limit:
function aumenta(id){
var valorAtual = 0;
setInterval(function(){
var elemento = document.getElementById(id);//pega a div com o número
var valor = elemento.innerHTML;
if (valorAtual <= 100) {
elemento.innerHTML = valorAtual++;
}
},20)
}
Finally, let's use the value inside the element to decide how far to go:
function aumenta(id){
var elemento = document.getElementById(id);//pega a div com o número
var valorAtual = 0;
var valorFinal = elemento.innerHTML;
setInterval(function(){
if (valorAtual <= valorFinal) {
elemento.innerHTML = valorAtual++;
}
},20)
}
Important to note that this has two problems:
The setInterval does not stop being called, it simply does not do anything. (but continues to toast energy)
It does not work well if the user removes the mouse from the top of the element and goes over it.
A correction for 1 ( jsfiddle ):
function aumenta(id){
var elemento = document.getElementById(id);//pega a div com o número
var valorAtual = 0;
var valorFinal = elemento.innerHTML;
var interval = setInterval(function(){
if (valorAtual <= valorFinal) {
elemento.innerHTML = valorAtual++;
} else {
clearInterval(interval);
}
},20)
}
There are also ways to solve the second problem, but it depends on how you want the function to behave.