Last Updated: February 25, 2016
·
9.686K
· danhodkinson

The jQuery slideToggle() Jump

the basic problem is:
you implement a basic slideToggle() but it jumps before it get to the bottom. It's based on jQuery working out the height wrong as it goes through its animation.

A quick fix is to simply add a fixed width to the element. But that doesn't help with responsive sites!

After much trial and error i found that if i added an each function to work out the height of each of my elements then this would sort it. But it worked out the height wrong as well! Nightmare!

What i did find is that if i didn't have my elements set to display:none at the start then it would slide perfectly with the correct heights. So i created this tiny function which works out the heights and then hides the elements. Also useful for those without js as the elements will be visible.

 $('.your-element').each(function() {
 $height = $(this).height();
 $(this).css('height', $height);
 $(this).hide();
});

$('.your-handler').click(function () {
$(this).next().slideToggle('slow');
$(this).toggleClass('active');
});

5 Responses
Add your response

Nice tips, I experienced this before ... one thing I don't like is hiding my element with js - so I wonder if your solution will work when hiding with css.

over 1 year ago ·

You absolute star. Tried lot's of other "fixes", this is the only one that actually worked. Might be because the issue was on a responsive site which the others didn't consider.

over 1 year ago ·

Thank you so much! This worked perfectly. Appreciated.

over 1 year ago ·

Are you sure this "jump" you are experiencing isn't being provoked by the flickering of margin collapse caused by the inline styles(overflow:hidden; padding-top: etc..) jquery injects on the element being animated?

In which case the more elegant solution would be to remedy your css.

over 1 year ago ·

Thank you so much!!!

over 1 year ago ·