2r83 2r83 - 6 months ago 14
Javascript Question

make sprite animation using javascript (every 5s)

i want to make my animation runs every 5sec using js

this is my html code

<div id="aa"></div>


and this is my css code

#aa{
width: 167px;
height: 169px;
background-image: url("sprite.png");
/*animation: play .2s steps(6) ;*/
}
@keyframes play {
from { background-position: 0px; }
to { background-position: -1002px; }
}


jsfiddle

Answer

You can play animation in class, then add and remove class of element every 5 second.

setInterval(function(){
    $("div").addClass("play");
    
    setTimeout(function(){
        $("div").removeClass("play");
    }, 1000);
}, 5000);
div {
    width: 100px;
    height: 100px;
    background: green;
}

.play {
    animation: play 1s;
}

@keyframes play {
    0% { margin-left: 0px; }
    50% { margin-left: 200px; }
    100% { margin-left: 0px; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>