Perelan
Perelan

Reputation: 55

Need Help: CSS3 Animation - Back and Forth

Here is my code to a simple animation. My intention is to make a image move back and forth, such as an attack animation. I have currently two problems; First: Once I press "Attack" (my button), the animation will not refresh. Second: The image/animation just go forth, but doesn't come back. Thanks

<body>


<button id="button">Attack</button>
<img src="Thor.png" width="152" height="112" id="sprite" />

<script>


button = document.getElementById("button");

function changeMargin() {
 var sprite = document.getElementById("sprite");
 sprite.style.transition = "margin 0.5s ease-in-out 0s";
 sprite.style.margin="0px 0px 0px 60px";
 sprite.style.f
}


button.onclick = function() {
    changeMargin();

};


</script>

</body>

Upvotes: 2

Views: 1059

Answers (1)

Aatish Sai
Aatish Sai

Reputation: 1677

You can create a reset function which will bring you sprite to normal position and use it with setTimeout() function. Click Here for Jsfiddle

<body>


<button id="button">Attack</button>
<img src="Thor.png" width="152" height="112" id="sprite" />

<script>
    button = document.getElementById("button");

    function changeMargin() {
    var sprite = document.getElementById("sprite");
    sprite.style.transition = "margin 0.5s ease-in-out 0s";
    sprite.style.margin="0px 0px 0px 60px";
    setTimeout(reset,1000);
}

function reset(){
    var sprite = document.getElementById("sprite");
    sprite.style.transition = "margin 0.5s ease-in-out 0s";
    sprite.style.margin="0px 0px 0px 0px";
}


button.onclick = function() {
    changeMargin();
};

</script>

</body>

Upvotes: 1

Related Questions