Why doesn't JavaScript run animation repeatedly in a simple counter?

Viewed 35

I am sorry if this is a trivial question but I am trying to design a simple counter using HTML and JS. It has an input form and whenever the user types a number and submits , the div counts from 0 to that number at interval of 1 second(using setInterval). The problem is I want that every time the number is updated, it should come in with "bouncing" animation. I am attaching the files here. For some reason, my code only makes the bounce once(when the number 1 comes) and not after that. Kindly suggest a simple tweak I can do in this code using just simple JavaScript. Thanks in advance for the guidance

function f() {
  
    var i = 0;
    var num = document.getElementsByTagName('input')[0].value
    num=parseFloat(num);

    var id=setInterval(function(){
        i++;
        document.getElementsByTagName('h2')[0].innerText=i;
        document.getElementsByTagName('h2')[0].style.animation="bounce 0.2s"
        if (i==num) { 
            alert("over!!")
            clearInterval(id);
            return;
        }},1000)
    

}



var button = document.getElementsByTagName('button');
button[0].addEventListener('click',f)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
    <style type="text/css">
        input {
            border: 2px solid black;
        }
        div {
            height: 100px;
            width: 100px;
            margin: auto;
            border: 2px solid black;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        @keyframes bounce {
            from{

            }
            to {
                bottom: 10px;
            }
        }
    </style>

</head>
<body>
    
    <input type="text" name="counter">
    <br>
    <button type="submit">Submit</button>

    <div><h2 style="position:relative;">0</h2></div>


    <script type="text/javascript" src="script2.js"></script>
</body>
</html>

1 Answers

The easiest solution is to listen to the end of the animation and set it back to none:

document.getElementsByTagName('h2')[0].onanimationend = function(){
    this.style.animation = 'none'
}
Related