DefaultPeak
DefaultPeak

Reputation: 123

Best way to restart animation with javascript (without using webkit)

Im coding an interactive element that turns to look towards you when you click on it. I just have an onclick event that adds a class with the animation. Unfortunately, after playing the first time the animation does not reset. I found a question asking the same thing, but it was much too advanced for me and additionally used webkit which I dont want to use for this. Is there a simple way to reset the animation?

.susanb{
    background-image:url('susanb.png');
    background-size:contain;
    width:18%; 
    height:45%;
    background-repeat:no-repeat;
    margin-top:12%;
    margin-left: 60%;
    position:absolute;
}

.susanbstare{
    animation-name: stare;
    animation-duration: 2s;
    animation-fill-mode: forwards;
}

@keyframes stare{
    0%{background-image: url('susanbstarin.png')}
    99%{background-image: url('susanbstarin.png')}
    100%{background-image: url('susanb.png')}
}
 <div class="susanb" id="susan"><div style="width:100%;height:100%;position:absolute;" onclick="stare();"></div>
    <script>
        function stare(){
            document.getElementById("susan").removeAttribute("class");
            document.getElementById("susan").setAttribute("class", "susanb susanbstare");
        }

    </script>
</body>

Upvotes: 0

Views: 41

Answers (1)

Bulent
Bulent

Reputation: 3411

.susanbstare {
  animation: stare 2s infinite;
}

BTW in JS, this is better

document.getElementById("susan").classList.toggle("susanbstare");

instead of these 2 lines

document.getElementById("susan").removeAttribute("class");
document.getElementById("susan").setAttribute("class", "susanb susanbstare");

Upvotes: 1

Related Questions