How does jQuery Slidedown get the final height of a hidden element before showing it?

I am trying to replicate jQuery slideDown() in GSAP, and I am having problems developing how jQuery calculates the height of an element that is currently hidden, as if it were set to height:auto .

I tried etching the code on GitHub but can't find the code that seems to do this in jQuery.fn.slideDown or jQuery.fn.animate that it calls.

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

  • Clone an element, place it on the screen and calculate its height.

    This will not work if the element or any of its children are tall with CSS styles that require the element to be in its original location in the DOM (for example, .accordianItem can only be styled if it is inside its .accordian ).

  • Display the element, remove height:0 and quickly calculate the height before hiding the element again, and then specify the animation.

    This can flash content quickly while calculating the height.

  • Use visibility:true to show it in place when calculating the height.

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

  • Calculate the height of the element before hiding it and save it in the data attribute so that we know it when we want to open the element later.

    It won. Works if any dynamic content changes the height of the element while it is hidden.

jQuery slideDown() "just works" every time, so I would be very interested to know how it works, but I just can't figure out where it does it. I am also surprised that GSAP cannot do this out of the box or that no one has used the right solution for this before.

Any help would be really appreciated.

+6
source share
1 answer

It turns out that if you use $.height() to get the height of an element using display:none , it does not return 0 , as you would expect, it actually sets visibility:hidden , position:absolute , etc. etc. sets display to block to give you the correct height. I guess this is what is used internally when you do a slide.

This answer helped me a lot.

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

Just to understand how this seems to avoid all the problems in my original question. It basically does the number (3), but avoids the problem of clicking on the bottom content down the page, because it also sets the position: absolute when the height is calculated. Very simple elegant solution

+6
source

Source: https://habr.com/ru/post/986446/


All Articles