I’m trying to create my own jquery image carousel in order to make myself more acquainted with it.
You can find the example here.
The carousel works by sliding the whole right, putting the last
Problem is if someone spams the next/prev button the whole carousel is moved to the right something not happening if the prev/next is used once per second or I set it to be clicked by jquery with a quick interval(500) for example.
the relevant parts of the code are:
function initUl(){
var li_width = $('.upper li').outerWidth();
var upper_width=$('.upper').outerWidth();
var lower_width=$('.lower').outerWidth();
var upper_pos = $('.upper').position();
var lower_pos = $('.lower').position();
lastBeforeFirst();
$('.upper').css({'left': upper_pos.left + (-1*li_width)});
$('.lower').css({'left': lower_pos.left + (-1*li_width)});
$('.upper').css({'width': upper_width + li_width});
$('.lower').css({'width': lower_width + li_width});
}
function moveBothRight(){
var speed = 200;
var li_width = $('.upper li').outerWidth();
var upper_pos = $('.upper').position();
var lower_pos = $('.lower').position();
$('.upper').animate({'left' :upper_pos.left + li_width}, speed,fixUpperPosR);
$('.lower').animate({'left' :lower_pos.left + li_width}, speed,fixLowerPosR);
}
function fixUpperPosR(){
var li_width = $('.upper li').outerWidth();
var upper_pos = $('.upper').position();
$('.upper').css({'left': upper_pos.left - li_width});
}
function fixLowerPosR(){
lastBeforeFirst();
var li_width = $('.upper li').outerWidth();
var lower_pos = $('.lower').position();
$('.lower').css({'left': lower_pos.left - li_width});
}
function lastBeforeFirst(){
var first = $('.upper ul li:first');
var last = $('.upper ul li:last');
$(first).before($(last));
first = $('.lower ul li:first');
last = $('.lower ul li:last');
$(first).before($(last));
}
This piece of code is responsible for moving everything right and its called on the next click the only difference on left is
$('.lower').css({'left': lower_pos.left + li_width});
and the firstBeforeLast(); call
Is this a browser thing(it cant update the css that quick) and therefore I should put a restriction on how often one can push the buttons, or i’m missing something?
The problem is due to the fact that animations are run asynchronously.
You need to stop the current animation and
jumpToEndwhenever a button is clicked.For example:
This will cause the current animation to complete immediately and update the css as needed.