简体   繁体   中英

jQuery slide toggle fires twice on double click

How can I prevent toggle from sliding twice on double click?

I have a button that triggers a slide toggle. It toggles fine if the button is clicked once but if the button is clicked twice the slide toggle slides out then immediately slides back in.

How can I get the slide toggle to stay out even on double click?

Code here: https://codepen.io/anon/pen/Ljgqjo

JS:

 $('button').on('click', function(){ $('#one').fadeOut('slow', function(){ $('#two').toggle('slide', {direction: 'right'}, 800, function(){ }); }); }); 
 .container{ width:300px; height:200px; overflow:hidden; } #one{ background:blue; width:300px; height:200px; } #two{ background:purple; width:300px; display:none; height:200px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <button>Click me to slide</button> <div class="container"> <div id="one"> </div> <div id="two"> </div> </div> 

Set a flag for tracking whether your animation is running. Check if it is set before allowing the click action to have any effect. Unset it once your animation is done:

var animating = false;
$('button').on('click', function(){
    if(!animating){
        animating = true;
        $('#one').fadeOut('slow', function(){
            $('#two').toggle('slide', {direction: 'right'}, 800, function(){
                animating = false;
            });
        });
    }
});

This has the additional benefit of protecting against triple clicks (and quadruple clicks, etc...)

Here you go with a solution http://jsfiddle.net/nya99njz/2/

 var sliding = false; $('button').on('click dblclick', function(){ if(!sliding){ sliding = true; $('#one').fadeOut('slow', function(){ $('#two').toggle('slide', {direction: 'right'}, 800, function(){ sliding = false; }); }); } }); 
 .container{ width:300px; height:200px; overflow:hidden; } #one{ background:blue; width:300px; height:200px; } #two{ background:purple; width:300px; display:none; height:200px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <button>Click me to slide</button> <div class="container"> <div id="one"> </div> <div id="two"> </div> </div> 

Instead of click use dblclick .

Hope this will help you.

You can change this line

$('button').on('click', function(){

To

$('button').on('click dblclick', function(){

Then it will do the same thing for click and double click.

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