0

Here is the working demo. http://jsfiddle.net/Evqqp/1/

Please check the demo to easily understand the issue. Click on the arrows fast and you will see the view mess up.

I understand it might be because of the 300ms animation i do. What is a clean way to handle the clicks such that it does not mess up the view. I can use a flag to check if the previous click action is complete. But i wanted to seek opinions if there is a better way to do this.

Code where i do the animate

$(".rightArrow").on("click", function () {
    if ((Math.abs(parseInt($(".slideBox").css("margin-left"))) + $(".mainDiv").width()) < $(".slideBox").width()) {
        $(".slideBox").animate({
            "margin-left": parseInt($(".slideBox").css("margin-left")) - $(".mainDiv").width()
        }, 300, checkRightArrow);
        $(".leftArrow").show();
    } else {
        $(".rightArrow").hide();
    }
});

Thank you

phpdev
  • 176
  • 1
  • 10
ksskr
  • 238
  • 4
  • 15

4 Answers4

1

Try .stop(true,true)

$(".slideBox").stop(true,true).animate({
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

Whenever working with animations you should always stop() the previous animation on the element before animating it again.

$(".slideBox").stop(true, true).animate(...

http://jsfiddle.net/Evqqp/4/

jbabey
  • 45,965
  • 12
  • 71
  • 94
  • There is problem here.. When you click fast, it will end up in a empty slide. – ksskr Nov 12 '13 at 15:59
  • @ksskr that is because your calculations are wrong, not because the animation is not fixed. you should not rely on the arrow being present to prevent the user from over-scrolling. this check should be in the click handler of the arrows. – jbabey Nov 12 '13 at 16:00
  • adding a check for is "animated" worked. I agree there are other ways to achieve what i did.Like setting margin-left to a var and then calling the animate, in which case i can use the stop like you suggested. Thanks though. working version here http://jsfiddle.net/Evqqp/5/ – ksskr Nov 12 '13 at 16:03
1

You need to add

event.stopPropagation();

after:

$(".rightArrow").on("click", function () {

so:

$(".rightArrow").on("click", function () {
     event.stopPropagation();
     ... 
napstercake
  • 1,815
  • 6
  • 32
  • 57
  • Don't think this would make any difference. The problem is with the animation queue, not any event handlers. – jbabey Nov 12 '13 at 15:59
1

Check if your element is currently animated with the following

if(!$('#myElement').is(':animated'))
{
    // Do your animation here
}
D4V1D
  • 5,805
  • 3
  • 30
  • 65