Kait Jardine
Kait Jardine

Reputation: 103

Trouble with image gallery jquery

I am doing a simple image gallery with only 2 images so far. I want the text to change with the picture. Currently the buttons don't work and I'm not sure why.

$(document).ready(function(){
var currPic = 0;
var pictures = ["sk8.jpg", "3dprntr.jpg"];
var text = ['x','y']
$("#next").click(function(){
    currPic++;
    $("#myImage").attr("src", pictures[currPic]);
    $("#desc").html(text[currPic]);
});
$("#prev").click(function(){
    currPic--;
    $("#myImage").attr("src", pictures[currPic]);
    $("#desc").html(text[currPic]);
})});

And the relevant html

<div id="gallery">
        <img src="sk8.jpg" border="0"/>
    </div>
    <div id="buttons">
        <input type="button" value="Previous" id="prev" />
        <input type="button" value="Next" id="next" />
    </div>
    <p id = "desc">text</p>

Upvotes: 0

Views: 42

Answers (1)

Mahesh Singh Chouhan
Mahesh Singh Chouhan

Reputation: 2588

Use same logic for text which you are using for image

Also fix couple of issues:

  • id is missing on image
  • var currPic should be var currpic, which you are using in your further code:

Try This:

Try out this code:

$(document).ready(function(){
    var currpic = 0;
    var pictures = ["https://gaytravel-destinations.s3.amazonaws.com/32491/united-states-beaches-and-scenery__small.jpg", "http://www.carolinasusi.com.au/cmsvltl/img/8/5/a/596dbfe80598106527a80d1ddddf6/Le-Marche%2C-Blue-skies-and-Le-Marche-scenery.jpg"];
    var texts = ["new text", "other new text"];
    $("#next").click(function(){
        currpic++;
        $("#myImage").attr("src", pictures[currpic]);
        $("#desc").text(texts[currpic]);
    });
    $("#prev").click(function(){
        currpic--;
        $("#myImage").attr("src", pictures[currpic]);
        $("#desc").text(texts[currpic]);
    }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gallery">
    <img id="myImage" src="https://gaytravel-destinations.s3.amazonaws.com/32491/united-states-beaches-and-scenery__small.jpg" border="0"/>
</div>
<div id="buttons">
    <input type="button" value="Previous" id="prev" />
    <input type="button" value="Next" id="next" />
</div>
<p id = "desc">text</p>

Upvotes: 1

Related Questions