开发者

second click beats first animate complete callback function

I have a button, when clicked, animates a div.

I am trying to make use of the $.animate() [complete] callback function, but running into a situation where clicking the button twice really fast causes the animation to run twice before the first animation's [complete] callback runs.

Please see this link for demo. http://jsfidd开发者_如何学Gole.net/zs2uf/3/

Any ideas how to prevent the second click from beating the first's callback?


You should disable the button immediately after it is clicked, and then do the animation.

You say you want to make it so that the button can only be clicked once, but you wait until the animation is done before disabling the button. This is why the program doesn't behave as you wish it to, since during the animation, the button could be clicked again.

Here is a how to make sure to button can only be clicked once:

$("#next").click(function(){

    var pos = parseInt($("#box").css("left")),
        newPos = pos + 100;

    // disable button immediately after the click
    // if you wait to disable, you give the user the chance to click twice
    $("#next").unbind('click');
    $("#next").attr("disabled", "disabled");

    $("#box").animate({
        "left" : newPos //move the box to the right by 100px
    }, {
        duration: 150
    });        
})

Working example

The unbind() may not be necessary in many browsers, but it ensures that the click event handler is actually removed from #next.


Fixed it take a look at this

http://jsfiddle.net/zs2uf/5/

Code

$("#next").click(function(){


    var pos = parseInt($("#box").css("left"));
    var newPos = pos + 100;

    if($("#box:animated").length == 0){

        $("#box").animate({
            "left" : newPos //move the box to the right by 100px
        }, {
            duration: 150,
            complete: function(){

            //after moving the box by 100px, disable the next button,
            //so that the box can move no further than 100px
            $("#next").attr("disabled", true);

            }
        });
    }





    //problem:
    //if you click the Next button twice really fast, 
    //the box moves twice before the button is disabled

})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜