Jordan Carter Jordan Carter - 5 months ago 10
jQuery Question

JavaScript/jQuery image slider issue

Fiddle: https://jsfiddle.net/8na2n5L2/

I'm trying to create an image slider, but for some reason just can't wrap my head around why this isn't working. I'm basically trying to create a slider where images come in from the right (off screen), and the center image gets pushed to the left (off screen). Then, when it comes time for that left image to go to the center again, it quickly goes back to the right again before going to the center.

jQuery(document).ready (function () {

var images = [];

//store the images in an array
jQuery('.main-image-slider').each( function () {
images.push(jQuery(this));
});

var i = 0;
var max = images.length - 1;

setInterval( function () {
if ( i > max) {
i = 0;
}

images[i].removeClass('main-image-slider-left').addClass('main-image-slider-right').delay(100).queue(function () {
images[i].removeClass('main-image-slider-right').addClass('main-image-slider-center').dequeue();
i++;
});


if (images[i - 1]) {
images[i - 1].removeClass('main-image-slider-center').addClass('main-image-slider-left');
}


}, 3000);


});

Answer

I get this console error "Uncaught TypeError: Cannot read property 'removeClass' of undefined".

This error is because the code will run i++ first, then run images[i].removeClass('main-image-slider-right')....

images[i].removeClass('main-image-slider-left').addClass('main-image-slider-right').delay(100).queue(function() {
  // the 'i' is already added 1, so it may equal images[max], so you got that error
  images[i].removeClass('main-image-slider-right').addClass('main-image-slider-center').dequeue();
});

You can move i++ into queue:

images[i].removeClass('main-image-slider-left').addClass('main-image-slider-right').delay(100).queue(function() {
  images[i].removeClass('main-image-slider-right').addClass('main-image-slider-center').dequeue();
  // after all the animation is done, at the end of queue update 'i'. 
  i++;
});

You can try this.

Note: don't forget to remove the i++ at the end of code.

Update

Update the jsfiddle code

At the edge of slides it will not update the class with if (images[i - 1]), wee need always update the class of previous slide. So I changed the code to

images[i == 0 ? images.length - 1 : i - 1].removeClass('main-image-slider-center').addClass('main-image-slider-left');
Comments