Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery Slidedown get final height of hidden item before showing it?

I'm trying to replicate jQuery slideDown() in GSAP and I'm having trouble working out how jQuery calculates the height of an item which is currently hidden as if it was set to height:auto.

I've tried trawling the code on GitHub but can't find any code which seems to be doing this in jQuery.fn.slideDown or jQuery.fn.animate which it calls.

There are several similar questions on SO and several solutions proposed, all of which seem to have their own problems:

  1. Clone the element, position it off screen and calculate its height.

    This won't work if the element or any of its child elements have a height set by CSS styles which require the element to be in its original place in the DOM (e.g. an .accordianItem might only be styled if it's inside its .accordian).

  2. Display the item, remove height:0 and quickly calculate the height before hiding the element again and then stating the animation.

    This might flash the content quickly while calculating the height.

  3. Use visibility:true to show it in place while calculating the height.

    This would stop the flash and still keep the element in the same position in the DOM for correct height calculation, but it would still push other items below it down because visibility:false items still have a height.

  4. Calculate the height of an item before it's hidden and store it in a data attribute so we know it when we want to open the item later.

    This won't work if any dynamic content changes the height of the item whilst it's hidden.

jQuery slideDown() "just works" every time so I'd be really interested to know how it works, but I just can't work out where it's doing this. I'm also surprised that GSAP can't do this out of the box, or that nobody has shared a proper solution to this before.

Any help would really be appreciated.

like image 373
jonhobbs Avatar asked May 03 '15 13:05

jonhobbs


1 Answers

It turns out that if you use $.height() to get the height of an element with display:none it doesn't return 0 as you would expect, it actually sets visibility:hidden, position:absolute etc. and sets display to block to give you the correct height back. I assume this is what's being used internally when doing a slidedown.

This answer helped me a lot.

jQuery: height()/width() and "display:none"

Just to be clear about how this seems to avoid all the problems in my original question. It's basically doing number (3) but avoiding the problem of pushing lower content down the page because it's also set to position:absolute while the height is being calculated. A very simple elegant solution

like image 186
jonhobbs Avatar answered Oct 14 '22 02:10

jonhobbs