How to make jquery toggle width animation stop midway to close again?
P粉238355860
P粉238355860 2024-03-19 23:49:40
0
2
381

Maybe this question is confusing, but let me give you an example, when I click the button that switches the width, the div continues to animate after pressing the button, which doesn't look amazing. What I want is for the div to stop halfway and go the other way, and not complete its existing animation when the button is pressed again.

$(document).ready(function() {
  $('.menuToggle').click(function() {
    $(".menuContainer").animate({
      width: 'toggle'
    });
  });
});
.menuContainer {
  height: 100px;
  width: 50px;
  float: left;
  position: relative;
  background-color: black;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menuContainer">
  <!-- Menu Items -->
</div>
<h4 class="menuToggle">Show Menu</h4>

Here's the violin so you can understand what I'm talking about. Try spamming the "Show Menu" button.

https://jsfiddle.net/x14usdga/5/

Thank you very much for your help, I've looked everywhere but can't seem to find any information on my problem.

P粉238355860
P粉238355860

reply all(2)
P粉567112391

You can check if the element is not animated before performing the animation

https://api.jquery.com/is/
https://api.jquery.com/animated-selector/

$(document).ready(function(){
  $('.menuToggle').click(function(){
    if( $('.menuContainer').is(':animated') ) { return false; }
    $(".menuContainer").animate({width: 'toggle'});
  });
});
.menuContainer{
    height: 100vh;
    width: 15vw;
    float: left;
    position: relative;
    background-color: black;
    display: none;
}


    
P粉701491897

You can use the .stop() method. Try this

$(document).ready(function() {
  $('.menuToggle').click(function() {
    $(".menuContainer").stop().animate({
      width: 'toggle'
    });
  });
});
.menuContainer {
  height: 100px;
  width: 50px;
  float: left;
  position: relative;
  background-color: black;
  display: none;
}


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template