jQuery Slide Toggle Problem #1

Lately I’ve been programming a lot of open/close drawers for websites. Many of them are simple and had a single button that opened and closed a single drawer. The slideToggle() method in jQuery with some nice easing worked wonderfully for accomplishing this, however as some of these projects required additional content to be opened/closed things quickly go down hill. See the code below to see what I mean.

Check out this Pen!

jQuery Slide Toggle Problem #2

One way around this is to use the callback function available to us in the slideToggle method that will fire once the slide is complete. Unfortunately many different combinations of slideUp and slideDown will all reveal various transition issues when the goal is to fully close a drawer before opening a new one. See the code below for adjustments to the problem #1.

Check out this Pen!

jQuery Slide Toggle Problem #3

I found that if reversed the logic to slideUp all divs and slideDown the matching div in the callback we get a lot closer to the correct timing, but it also creates a problem for us when clicking on an already open drawer. Adding a delay to the complete/callback function helps to smooth out the timing when switching between drawers as well but this is not a very predictable solution. If you remove the delay in the code below you’ll see how it helps.

Check out this Pen!

 

jQuery Slide Toggle Solution

Ultimately .slideToggle() is very rarely going to be used on it’s own to solve problems like this. In this case the solution is to use a little known jQuery method called .promise(). The .promise() method is tremendously useful because it will wait for any set of matched elements to completely finish animating, even if multiple animations are present.

Check out this Pen!

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop us a note so we can take care of it!

Archives

All entries, chronologically...