Max Pain
Max Pain

Reputation: 1237

a div animates outside the screen with rapid clicking

I have this code:

$(document).ready(function(){

    $(".subscriptions").click(function (){

        if($(".pollSlider").css("margin-right") == "-200px"){
            $('.pollSlider').animate({"margin-right": '+=200'});
            }else{
            $('.pollSlider').animate({"margin-right": '-=200'});
            }
        });

//other exceptions

if($(".pollSlider").css("margin-right") > "200px"){
    $(".pollSlider").css({'margin-righ':'200px'});
    }
if($(".pollSlider").css("margin-right") < "0px"){
    $(".pollSlider").css({'margin-righ':'0px'});
    }
 }); 

this is the css:

.pollSlider{
    overflow: auto;
    top:0px;
    position:fixed;
    height:100%;
    background:red;
    width:200px;
    right:0px;
    margin-right: -200px;
    z-index:100;
}

I have a div, when the user click a button the div slides from the left 200px into the screen and when the user clicks the same button again the div animate to the right 200px. This system works very good but the problem is, if the user kept clicking while the div animating left or right, the div will animate out side the screen (to the right) and does not come back again when the user clicks again. So I tried to add the //other exceptions but those if statements did not work. How can I fix this problem ?

Upvotes: 0

Views: 157

Answers (2)

thirdender
thirdender

Reputation: 3951

I've created a Demo where I tried to achieve the effect you're trying to produce. As mentioned in the comments, jQuery .stop(…) is used to empty the animation queue before starting the next animation.

I also changed the units from relative (+=200 and -=200) to fixed numbers (0 and -width). If you assume the animation will be stopped midstream and you'll need to animate back, you'll need to use either fixed numbers, or do the calculation on the fly before each new animation.

Upvotes: 1

bumerang
bumerang

Reputation: 1846

My solution for this kind of problem is to add a global variable nad set it to false after user click and set it back to tru when the animation is done:

var allowAnimate = true;
$(document).ready(function(){

$(".subscriptions").click(function (){
    if(allowAnimate){
    if($(".pollSlider").css("margin-right") <= "-200px"){
        allowAnimate = false;
        $('.pollSlider').animate({"margin-right": '+=200'}, function(){allowAnimate = true});
        }else if($(".pollSlider").css("margin-right") >= "200px")){
        $('.pollSlider').animate({"margin-right": '-=200'}, function(){allowAnimate = true});
        }
    }
    });

//other exceptions
....

So if User click a button the variable allowAnimate is checked if its true, I set it to false, and the animation will began, on the animation callback function I set it back to true.

Upvotes: 0

Related Questions