I am trying to create a very simple slideshow just for the learning purpose. I want to slide the list items to the left automatically in a loop.
I have come up with following code, it slides but I am unable to set the correct position for the slide (as it only flashes and disappears). Check the demo to see the problem:
Here's my fiddle
Html:
<div class="wrap">
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
Jquery:
var width = $('li').width();
var totalWidth = $('li').length * width;
var count = $('li').length;
var first = $('li').eq(0);
var last = $('li').eq(count-1);
$('ul').css({
'width' : totalWidth
});
first.addClass('active');
var start = function() {
target = $('.active').index();
target === last ? target = 0 : target = target+1;
nextSlide(target);
};
var nextSlide = function(target) {
//console.log(target);
$('.active').animate({'left':'-'+ width*target +'px'},300);
$('li').removeClass('active').eq(target).addClass('active');
};
setInterval(function () {
start();
}, 3000)
I have changed Class name
only and it works. You was using wrong class active
for animation, instead of this you should animation your complete <ul>
so i have used class of ul list
for left animation:
What i have changed:
$('.active').animate({'left':'-'+ width*target +'px'},300);
to
$('.list').animate({'left':'-'+ width*target +'px'},300);
your problem is you don not understand where your li's are actually positioned on way to solve it is to just slide the ul like so:
function slide(){
$('ul').animate({'left':$('ul').position().left - width},300);
}
http://jsfiddle.net/32v5q59L/5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With