简体   繁体   中英

disable a button click with jquery on a slide down div

so I have a slide down div that reveals a menu, but if you rapidly click the button the results are less than desirable. I would like the button to do nothing until the animation is complete, and likewise on the other end. This is what I have so far

$(function () {
    $('#header .exploreExpandBtn a').live( 'click', function (e) {
        e.preventDefault();
        $(this).parent().toggleClass('open');
        $('.exploreNav').stop(true,true).slideToggle();
    })
})

and my html

<h2 class="exploreExpandBtn logoBtn"><a class="ir" href="#menu-explore-menu" <strong>Explore</strong></a></h2>

<div class="exploreNav clearfix">
<div class="bgShadow clearfix">
<div class="wrap clearfix">
<?php wp_nav_menu( array( 'theme_location' => 'global-explore-menu' ) ); ?>
</div>
</div>
</div>

Try:

$(function () {
    $('#header .exploreExpandBtn a').on('click', function (e) {
        e.preventDefault();
        var $this = $(this);
        $('.exploreNav:not(:animated)').stop(true, true).slideToggle(400, function(){
            $this.parent().toggleClass('open');
        });
    });
});

Note that I chose 400 as the duration of the animation as it is the default duration that slideToggle is shipped with. Docs: http://api.jquery.com/slideToggle/

Use a variable to check if the animation is in progress or not

var animDone = true;

Before animating your div

//Set to false before animating
animDone = false;
$('.exploreNav').stop(true,true).slideToggle(500,function(){
    //Then true when animation has been done
    animDone = true;
});

In your button click callback or whereever you want, test the variable and return false if the animation is in progress :

if(!animDone)
    return false;

Disable the button on click and enable it once the animation is complete.

$(function () {
    $('#header .exploreExpandBtn a').live( 'click', function (e) {
        e.preventDefault();
        $(this).parent().toggleClass('open');
        $(this).attr('disabled', 'disabled');
        var that = this; //to refer to the link in the complete function
        $('.exploreNav').stop(true,true).slideToggle(
                 {complete: function() { $(that).removeAttr('disabled')}
        );
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM