i have a basic jQuery image slider (code below) which slides automatically on a timer. I'd like it to loop but it's getting stuck after the last slide. I'm just starting out with jQuery so may be missing something obvious but I can't work out what's going wrong! Can anyone help please?
Here's the code...
$(document).ready(function() {
//INDEX IMAGES SLIDER
$(function() {
//configuration
var width = 720;
var speed = 1000;
var pause = 3000;
var current = 1;
//cache DOM
var $slider = $('#slider');
var $slides = $slider.find('#slides');
var $slide = $slides.find('.slide');
setInterval(function() {
//move image the defined width and speed to the left
$slides.animate({'margin-left': '-='+width}, speed, function() {
//count number of slides and loop back to first from last
current++;
if (current === $slides.length) {
current = 1;
$slides.css('margin-left', 0);
}
});
}, pause);
});
});
#slider {
width: 720px;
height: 400px;
overflow: hidden;
}
#slider #slides {
display: block;
width: 2880px;
height: 400px;
margin: 0;
padding: 0;
}
#slider .slide {
float: left;
list-style: none;
height: 400px;
width: 720px;
}
#slider .slide img {
width: 100%;
}
<div id="slider">
<ul id="slides">
<li class="slide"><img src="images/sp_1.png"></li>
<li class="slide"><img src="images/ss_1.jpg"></li>
<li class="slide"><img src="images/sd_1.jpg"></li>
<li class="slide"><img src="images/sp_1.png"></li>
</ul>
</div>
you have a little mistake. $slides.length is 1 because there is only 1 div with that id. Therefore, what you really want to use is $slide.length in your if statement. Because there are that number of slides on your page. So if you change your if statement as follows it should work:
if (current === $slide.length) {
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments