Switch jquery between multiple images on click

I am trying to use jquery to switch between three images as soon as you click on the image. After clicking on the third image, it switches back to the first image.

Is there a way to adapt the following to switch between more than two images, and to allow it more than switch once?

JQuery

$(document).ready(function() { $("#clickMe").click(function() { $("#myimage").attr({src : "picture2.png"}); }); }); 

HTML

 <div id="clickMe"><img id="myimage" src="picture1.png" /></div> 

Thanks.

+4
source share
3 answers

This should do the following:

 $(document).ready(function() { $("#clickMe").click(function() { var src = $('#myimage').attr('src'); //if the current image is picture1.png, change it to picture2.png if(src == 'picture1.png') { $("#myimage").attr("src","picture2.png"); //if the current image is picture2.png, change it to picture3.png } else if(src == "picture2.png") { $("#myimage").attr("src","picture2.png"); //if the current image is anything else, change it back to picture1.png } else { $("#myimage").attr("src","picture2.png"); } }); }); 
+4
source

It works:

 $(document).ready(function () { var i = 1; // Used to keep track of which image we're looking at $("#clickMe").click(function () { i = i < 3 ? i + 1 : 1; $("#myimage").html("picture#.png".replace("#", i)); }); }); 

Online demo: http://jsbin.com/afito

+2
source

All Articles