views:

479

answers:

3

Hi, I'm trying to use jquery to switch between three images once you click on the image. Upon clicking on the third image, it switches it back to the first picture.

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

$(document).ready(function() {
$("#clickMe").click(function() {
$("#myimage").attr({src : "picture2.png"});
});
});
<div id="clickMe"><img id="myimage" src="picture1.png" /></div>

Thanks.

A: 

This is link might be helpful

http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery/

joe
+2  A: 

This should do that:

$(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");
        }
    }); 
});
karim79
You've got a small typo in your code: elseif should be else if
moff
@Moff - thanks, fixed.
karim79
This works perfectly, thanks!
John
+2  A: 

This 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

moff