Hollow Gallows Hollow Gallows - 2 months ago 12
jQuery Question

How can I make a slideshow using jQuery?

I wanted to try using jQuery to make a slideshow, but I'm finding it difficult to get make an array of my classes

slides
. Is there something wrong with the code below?

$(document).ready(function() {
var slideIndex = 0;
var slides = $('.slides');
slides[slideIndex].show();

$('.next').click(function() {
var i;
if (slideIndex > slides.length) {
slideIndex = 0;
}

for (i = 0; i < slides.length; i++) {
slides[i].hide();
}

slideIndex++;
slides[slideIndex].show();

var pageNum = slideIndex + 1;
$('.numbertext').innerHTML(pageNum + "/" + slides.length);
});

$('.prev').click(function() {
var i;

if (slideIndex < 0) {
slideIndex = slides.length;
}

for (i = 0; i < slides.length; i++) {
slides[i].hide();
}

slideIndex--;
slides[slideIndex].show();
});
});

Answer Source

Your slides array will have DOM nodes, not jQuery objects. So when you want to apply a jQuery method on one individual element, like hide() or show() you must get the element as a jQuery object. It is better not to take the array element with [i] for that purpose, but apply the eq(i) method: that will give you a jQuery object for which the show/hide methods are available.

For example, change:

slides[slideIndex].show();

to:

slides.eq(slideIndex).show();

...etc.

Note that for related reasons it is not necessary to loop over slides to hide each element. You can just hide the collection:

Replace:

for (i = 0; i < slides.length; i++) {
    slides[i].hide();
}

with:

slides.hide();

Another issue is your range checking for slideIndex. It is placed at the wrong spot, and the slideIndex > slides.length should be slideIndex >= slides.length

Place those if conditions just after you do slideIndex++ or slideIndex--.