Reputation: 2180
I am trying to develop an image slider using jQuery just for learning purposes. My code is working properly but when I reach on last slide its works very awkward I just want when user on first slide then he click on next button then user jump to first slide. Please check the given link and please help me out ...
HTML
<div id="wrapper">
<div class="slider_cont">
<ul>
<li>first slide</li>
<li>second slide</li>
<li>third slide</li>
<li>fourth slide</li>
</ul>
</div>
<div class="button">
<button data-dir="prev">pev</button>
<button data-dir="next">next</button>
</div>
</div>
CSS
body{margin:0; padding:0;}
*{margin:0; padding:0;}
#wrapper{width:300px; margin:0 auto; padding:100px 0 0;}
.slider_cont{width:300px; height:100px; overflow:hidden; position:relative;}
.slider_cont ul{width:10000px; position:absolute;}
.slider_cont ul li{ list-style:none; float:left; width:300px; height:100px; text-align:center; color:#fff; background:#ccc;}
.button{padding:30px 0 0;}
.button button{padding:10px; margin:0 20px 0 0;}
SCRIPT
var imageWidth = $('.slider_cont ul li').width(),
imageLen = $('.slider_cont ul li').length,
totalWidth = imageWidth * imageLen,
current = 1,
lastWidth = totalWidth - imageWidth;
$('button').on('click',function(){
var direction = $(this).data('dir');
(direction == 'next')?++current:--current;
var Unit = (direction == 'next')?'-=':'+=';
var curUnite = Unit+imageWidth;
alert(curUnite)
if(current!=0)
{
$('.slider_cont ul').animate({
left: curUnite+'px',
}, 500, function() {
// Animation complete.
});
}
if(current==0)
{
$('.slider_cont ul').animate({
left: '-='+lastWidth+'px',
}, 500, function() {
current = imageLen;
});
}
if(current>imageLen)
{
$('.slider_cont ul').animate({
left: '0px',
}, 500, function() {
current = 1;
});
}
})
Any help and suggestion would be appreciated :)
Upvotes: 0
Views: 299
Reputation: 205987
var imageWidth = $('.slider_cont ul li').width(),
imageLen = $('.slider_cont ul li').length,
counter = 0;
$('button[data-dir]').click(function(){
var dir = $(this).data('dir') == 'next' ? counter++ : counter-- ;
counter = counter<0 ? imageLen-1 : counter%imageLen ;
$('.slider_cont').stop().animate({scrollLeft: imageWidth*counter},800);
});
Upvotes: 1
Reputation: 49909
Your doing this:
if (current == 0) {
$('.slider_cont ul').animate({
left: '-=' + lastWidth + 'px',
}, 500, function () {
current = imageLen;
});
}
else if (current > imageLen) {
$('.slider_cont ul').animate({
left: '0px',
}, 500, function () {
current = 1;
});
}
else if (current != 0) {
$('.slider_cont ul').animate({
left: curUnite + 'px',
}, 500, function () {
// Animation complete.
});
}
Thats where the strange animation comes from. Because you queue the second one. Whichc jumps back to the start. Put the first animation ins the else statement. And you won't have the strange jumps.
Live example: http://jsfiddle.net/VMZ8J/3/
Upvotes: 2