The problem is that you are using the content of the widget to two effects:
- Save current value (
valorInicial
).
- Save the final desired value.
When it reaches the line to change the innerHTML, it ends up changing the final value by drag.
Let’s then 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 us 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 bear in mind that this has two problems:
- The setInterval does not stop being called, it simply goes to do nothing. (but continues to burn energy)
- It does not work well if the user removes the mouse from the top of the widget and moves it again.
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.
answered again...
– fotanus