Reputation: 3111
i have a slider, which I want to stop at the last slide (margin-left:-2586px;).
im using the below jquery to animate between each slide on click (currently only going left).
the problem is the slider will go past the -2586px if you click the #left quickly. how can i make sure this doesnt happen?
$('#left').click(function(){
var left = 862;
if($('#slider-visible').css('margin-left') == '-2586px'){
}
else{
$('#slider-visible').animate({'margin-left':'-=' + left},500);
}
});
thanks!
Upvotes: 1
Views: 244
Reputation: 7199
Check if the element is in the middle of animation. If it is, don't run the animation again.
else{
if($('#slider-visible:animated').length == 0){
$('#slider-visible').animate({'margin-left':'-=' + left},500);
}
}
Upvotes: 1
Reputation: 205987
Why is this wrong:
$('#left').click(function(){
var left = 862;
if($('#slider-visible').css('margin-left') == '-2586px'){
}
else{
$('#slider-visible').animate({'margin-left':'-=' + left},500);
}
});
not stopping an animation queue ( using .stop()
), and using -=
and trying to use ==
to detect an exact position.... wrong
A correctly built slider has a .stop()
and a...
counter !
The animations usually are built depending on:
left: - counter*oneSlideWidth
counter = counter % numberOfSlides
-1
(inexistant left slide) than you set it to the numberOfSlides-1
and you do again:
$('#slider').stop().animate({left: -counter * slideWidth });
Basic sliders logic:
var galleryWidth = $('#gallery').width(),
counter = 0,
numberOfSlides = $('#gallery .slides').length;
$('#prev, #next').click(function() {
if( this.id=='next'){
counter++;
counter = counter % numberOfSlides ; // will reset to '0' if both match
}else{ // prev was clicked
counter--;
if(counter==-1){
counter = numberOfSlides-1 ;
}
}
$('#slider').stop().animate({left: - counter * galleryWidth }, 700);
});
OR simply:
$('#prev, #next').click(function() {
var myId = this.id=='next' ? counter++ : counter-- ;
counter = counter===-1? numberOfslides-1 : counter%numberOfSlides;
$('#slider').stop().animate({left: - counter * galleryWidth }, 700);
});
Upvotes: 1
Reputation: 955
i think if you test this , it will work :
var element=$('#left');
else{
$('#slider-visible').animate({element.style.marginLeft=left},500);
}
Upvotes: 0