Question

I am sure it is just me not understanding JavaScript fundamentals properly. But could someone point out as why I have the impression that my if statement evaluates to true, on event bubbling, even though the statement inside the if statement should evaluate to false ?

The if(sFormula > 168) seem to work as intended when I press the html < a > tag once at a time, but if I rapidly click on it, everything seems to go crazy.

Here is a jsFiddle with the code: http://jsfiddle.net/twimB/pGHrP/ and below is just a snippet of the whole.

I would greatly appreciate if someone could take his/her time to explain.

Thanks.

Html

<a href="#" id="right">&raquo;</a>

jQuery

$("#right").click(function(event){
    event.stopImmediatePropagation();
    if(busy == false){
        busy = true ;
        var parentMargin = $(".wrap").offset().left;
        var parentWidth = $(".wrap").width();
        var carouselMargin = $(".block").offset().left;
        var carouselWidth = $(".block").width();
        var rFormula = carouselWidth - ((parentMargin - carouselMargin) + parentWidth);
        $(".pLeft").text("");
        $(".pRight").text("if ( rFormula > 0 ) {perform slide} fFormula is: " + rFormula);
        if(rFormula > 168){
            $(".block").animate({"left": "-=168px"}, "slow");
        }
        busy = false ;
    }
});
Was it helpful?

Solution

The .animate() method doesn't stop the script execution. What happens is that it starts the animation and script execution continues, and busy is immediately set to false.

What you need is to set the flag only after the animation has finished using a callback function:

if(rFormula > 168){
    busy = true;
    $(".block").animate({"left": "-=168px"}, "slow", function() { busy = false });
}

(Note that I also moved setting the flag here because there's no benefit in setting it before the animation begins.)

Demo: http://jsfiddle.net/pGHrP/1/ (I updated only the right button.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top