jQuery animation: Ignore double click

后端 未结 4 1676
闹比i
闹比i 2021-01-05 03:51

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 mes

相关标签:
4条回答
  • 2021-01-05 04:25

    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
       }
       ....
     })
    
    0 讨论(0)
  • 2021-01-05 04:32

    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();
            });
        }
    });    
    
    0 讨论(0)
  • 2021-01-05 04:42

    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.

    0 讨论(0)
  • 2021-01-05 04:42

    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.

    0 讨论(0)
提交回复
热议问题