Search code examples
jqueryimageloopsbuttonclick

jQuery to cycle through images on button press


Complete novice at coding so apologies in advance but I'm tearing my hair out about this question!

Task at hand

I'm trying to get jQuery to cycle through a set of images upon a button click in an endless loop.

I've got the following so far and I can't find any holes in my logic, but it just doesn't seem to work. If someone could have a quick look over it and maybe put it all into a working jsfiddle I would very much appreciate it!

      $(document).ready(function() { 
      $(“#button”).click(function() {

    var src = $('#myimage').attr('src');

    //if the current image is picture1.png, change it to picture2.png
    if(src == 'pic1.png') {
        $("#myimage").attr("src","pic2.png");

    //if the current image is picture2.png, change it to picture3.png 
    } else if(src == "pic2.png") {
        $("#myimage").attr("src","pic3.png"); 

    //if the current image is anything else, change it back to picture1.png
    } else {
        $("#myimage").attr("src","pic1.png");
    }
}); 

UPDATE I think I may be doing something wrong with my actual fiddle? https://jsfiddle.net/pj2wvcdx/


Solution

  • Here's a working example. It's all based on your code, and the only thing I changed is that you used the wrong quotes for "#button", but that might have been a copy-paste-thing? And you didn't close the click function.

    $(document).ready(function() { 
      $("#button").click(function() {
        var src = $('#myimage').attr('src');
    
        //if the current image is picture1.png, change it to picture2.png
        if(src == 'http://www.libpng.org/pub/png/PngSuite/f01n2c08.png') {
            $("#myimage").attr("src","http://www.libpng.org/pub/png/PngSuite/f02n2c08.png");
    
        //if the current image is picture2.png, change it to picture3.png 
        } else if(src == "http://www.libpng.org/pub/png/PngSuite/f02n2c08.png") {
            $("#myimage").attr("src","http://www.libpng.org/pub/png/PngSuite/f03n2c08.png"); 
        //if the current image is anything else, change it back to picture1.png
        } else {
            $("#myimage").attr("src","http://www.libpng.org/pub/png/PngSuite/f01n2c08.png");
        }
        console.log("Src is: " + $("#myimage").attr("src"));
      })
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="button" >Cycle</button>
    <img src="http://www.libpng.org/pub/png/PngSuite/f01n2c08.png" id="myimage"/>

    The error in your snippet is that you're never going from 1 -> 2.

    enter image description here