muzzi
muzzi

Reputation: 372

How to create image animation in javascript

I am trying to create an image animation which starts by clicking on Start Animation button and should alternate with another picture every half a second until I click on Stop Animation button. When I run this code, it does not output anything. what is wrong with the following code ?

My coding:

<button onClick="StartAnimation()">
Start Animation
</button>

<button onClick="StopAnimation()">
Stop Animation
</button>

<script>
    var counter;
    var Schedule;
    function StartAnimation(){
    var images = document.getElementById("fish"); 
   images.src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";


    Schedule = setInterval(animationfunction,5000);

} 
function animationfunction(){
    var fish_img = document.getElementById("fish");
    fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
}
function StopAnimation(){
    clearInterval(Schedule);
}

Upvotes: 1

Views: 1615

Answers (2)

Khakwani
Khakwani

Reputation: 70

Try to add this function. Your code looks like, you only want to change your image once. Try to add loop or you can complete in one if-else statement like this.

function animationfunction(){

if(image == "happy"){
    image = "sad";
    fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
}else{
    image="happy";
        fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
}
}
function StopAnimation(){
    clearInterval(Schedule);
}

Upvotes: 1

Ethan Strauss
Ethan Strauss

Reputation: 36

You've misnamed your function function StarAnimation(){ should be function StartAnimation(){

Upvotes: 2

Related Questions