Forum Moderators: open

Message Too Old, No Replies

Recreating a .slideUp( ) / .slideDown( ) Effect in Pure Javascript

         

l008comm

12:55 am on Feb 14, 2021 (gmt 0)

10+ Year Member Top Contributors Of The Month



I have spent so many days fighting with this, googling page after page after page. I can find an army of half-assed solutions but I can't find any working solutions:

How can I write my own jQuery style slideDown( ) functions in pure javascript.

It always starts with CSS transitions. You add a height transition to a div and you think you can just change its height and life will be good. But big surprise, that doesn't work. You can't animate a change from '0px' to 'auto'. You can only change items from one fixed number to another. But most div's I animate don't have set heights. Their height is determined by their content. I've played around with pre-measuring the div's on page load, then hiding them and setting their height to 0px. It kinda works, sometimes. Then often times it doesn't work, for no particular reason.

There's also the max-height hack. But that crops the animation in a terrible way. This solution does not work for me AT ALL.

I've tried just searching through jQuery to see how they do it. It works basically universally in jQuery, and without it, it's very hard to get consistent behavior if you can get any animation at all. But I search all over the file and I can't find anything. slideUp() seems to be an alias for a function that does essentially nothing.

Ideally I'd love to be able to make my own easily portable function I can just give any id to and it will zip it out of existence. In an earlier attempt, I ended up with functions so big, so many lines of code, it was becoming an unmanageable disaster so I scraped it.

There must be some way to do this? It can't be impossible? But it sure seems like it is.

NickMNS

3:06 am on Feb 14, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



But most div's I animate don't have set heights. Their height is determined by their content.

So measure the height of the children, by looping through each child of the parent and measuring it's height.
I've played around with pre-measuring the div's on page load, then hiding them and setting their height to 0px. It kinda works, sometimes. Then often times it doesn't work, for no particular reason.

Why at load, make the measurement when the slide event is triggered. Like that you have an accurate measure of the state at that moment. This assumes that nothing else can change the height of the elements.