search

Home  >  Q&A  >  body text

How to make jquery toggle width animation stop midway to close again?

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粉238355860P粉238355860271 days ago386

reply all(2)I'll reply

  • P粉567112391

    P粉5671123912024-03-20 16:50:32

    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;
    }
    
    
        

    reply
    0
  • P粉701491897

    P粉7014918972024-03-20 14:09:48

    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;
    }
    
    
    

    reply
    0
  • Cancelreply