jQuery animation: Ignore double click

2019-02-13 03:54发布

I have a simple jQuery animation that moves a div to the right or left, upon a .click() event.

However, if the user clicks the event twice, it fires twice, which messes up the formatting.

Here's an example of what I have:

$('a#right').click( function () {

if ($(this).is(':visible')) {

    $('#slide').animate({right: '+=257'}, 400, function () {
    slide_button();
    });

    }
});

The function slide_button() will check to see if the position of the div is within acceptable limits for the user's viewpoint. If so, it will allow the right or left button to be visible. If it is outside of the limits, it will hide the buttons.

It works well, except if I click it twice--then it will just slide right off the page.

Is there a way to work with this to ignore double clicks?

4条回答
小情绪 Triste *
2楼-- · 2019-02-13 04:09

I normally get around this by setting a global variable and run an if like

 clicked = true;
 $(div).click(function(){
   if (!clicked){
       clicked = true;
       Your function with a callback setting clicked to false
   }
   ....
 })
查看更多
男人必须洒脱
3楼-- · 2019-02-13 04:14

You could .unbind() the click event once clicked which will prevent it from executing multiple times:

$('a#right').click(function () {
    $(this).unbind('click');
    ...
});

Once the animation completes you could rebind it if you need to be able to click again.

查看更多
在下西门庆
4楼-- · 2019-02-13 04:21

Just check if element is already animating:

$('a#right').click( function () {
    if ($(this).is(':visible') && !$('#slide').is(':animated')) {
        $('#slide').animate({right: '+=257'}, 400, function () {
            slide_button();
        });
    }
});    
查看更多
Root(大扎)
5楼-- · 2019-02-13 04:23

You can use one() in jquery:

$('a#right').one("click", function () {
    slide($(this));
});

function slide(obj) {
    if (obj.is(':visible')) {
        $('#slide').animate({right: '+=257'}, 400, function () {
            slide_button();
            $('a#right').one("click", function () {
              slide($(this));
            }
        });
}

After the animation is completed, the click event is bound to the link again and it can be executed at most once.

查看更多
登录 后发表回答