javascriptjqueryjquery-eventsslidetoggle

Stop animation using slideToggle


I have a button <button class="foo">Foo</button> with an event handler attached to it that expands or collapses a block using .slideToggle()

$('.foo').on('click', function () {
  const fooBlock = $(this).next();
  fooBlock.slideToggle(() => {
    fooBlock.toggleClass('hidden');
  });

If a user clicks the button when an animation is in transition then the click is queued. How do I stop the animation if the user clicks the button while the animation is already executing?


Solution

  • A much better solution is to just use stop(true) to clear the queue on successive clicks. This means the UI is still responsive to user input during the animation and also prevents the animations building up. Try this:

    $('.foo').on('click', function() {
      const fooBlock = $(this).next();
      fooBlock.stop(true).slideToggle(() => {
        fooBlock.toggleClass('hidden');
      });
    });