Lachlan Jansen Lachlan Jansen - 6 months ago 21
Javascript Question

JQuery Gallery next button not working properly?

I am trying to create a basic gallery using JQuery.

The basic idea is that all image files are called x.png (where x is a number), and the program adds a number to the current number creating x+1.png and so on.

The code i have is:

function gal2(){
var amount = $(".imagelist > img").length;
var next = $("#display").attr('src').replace('.png', '');
if ($("#display").attr('src').replace('.png', '') >= amount) {
$("#display").attr('src', next+".png");
next++;
} else {
$("#display").attr('src', next+".png");
next++;
};
}


gal2 is called on a button press
<input type="button" onclick="gal2()">
,


.imagelist
is a div containing the images,


#display
is the main image being shown,


Example Website

The problem is that nothing happens except if one is selected than it will back to the original one every time.


P.S: It's for a year 9 secondary school project

Answer

You made some edits to your script and now it work fine : https://jsfiddle.net/IA7medd/qwmt7Lep/2/

function gal2(){
    var amount = $(".imagelist > img").length;
    var current = parseInt($("#display").attr('src').replace('.png', ''));
    var next = current + 1;
    if (current < amount) {
        $("#display").attr('src', next+".png");
    } else {
        $("#display").attr('src', "1.png");
    };
}
Comments