d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Js Animating Dropdown
Add Reply New Topic New Poll
Member
Posts: 6,490
Joined: Feb 7 2018
Gold: 152.00
Mar 9 2022 05:36pm
I currently have an issue where i'm using max-height to animate drop down FAQ's

My issue is, because there is a fixed max-height on the active class, if they FAQ answer is way shorter than the max-height, the animation is delayed

How can I calculate the height of the answer div and set the max-height to the correct height value, to smooth out the animation

Code
<div class="faq_card">
<i class="material-icons drop_down">expand_more</i>
<p class="bold">Question?</p>
<div class="answer">
<p>Answer</p>
</div>
</div>


CSS:
Code
.answer {
max-height: 0;
display: block;
overflow: hidden;
visibility: hidden;
-webkit-transition: 0.2s;
transition: 0.2s;
}

.answer.show {
max-height: 600px;
visibility: visible;
}


Javascript Code:
Code
$('.faq_card').click(function () {
$(this).find('.answer').toggleClass('show');
$(this).find('.drop_down').toggleClass('active');
});


This post was edited by Strickland on Mar 9 2022 05:37pm
Member
Posts: 12,703
Joined: May 17 2013
Gold: 12,935.00
Mar 11 2022 04:50am
remove the max-height: 0 property on the hidden answer. If you use visibility: hidden, you should be able to get the dimensions of the answer div even if it's not visible to the user.


If you want to keep the CSS animation, you could use a CSS variable and update that from JS:

Code

:root {
--max-height-dropdown: 0px;
}

// use it in your CSS:
.answer.show {
max-height: var(--max-height-dropdown);
visibility: visible;
}


// then you can update that variable in JS:
const root = document.documentElement;

root.style.setProperty('--max-height-dropdown', 400 + "px");


This post was edited by Klexmoo on Mar 11 2022 04:54am
Member
Posts: 3,372
Joined: Sep 2 2006
Gold: 22,951.70
May 15 2022 11:02pm
Avoid all of this mess by using transform properties. Ez

Code
.answer {
overflow: hidden;
-webkit-transition: 0.2s;
transition: 0.2s;
background: blue;
transform: scaleY(0);
transform-origin: top;
}

.answer.show {
transform: scaleY(1);
}
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll