Answer the question
In order to leave comments, you need to log in
How to implement dropdown for different amount of text?
I am making a block that can collapse, thus hiding part of the content, but the problem arises in the fact that it is impossible to guess the height of the content when collapsed at different resolutions, part of the line can peek out, because the font size is different and the amount of text is different, where 1 paragraph is large, and where then 2 small ones. The option to divide into 2 blocks, the one that is always visible and the second that is hidden / deployed, does not fit. What can be done in this case?
<div class="dropdown" aria-expanded="false" data-height="высота в свернутом виде">
<div class="dropdown__content">
<!-- какой то текстовый контент -->
</div>
<button class="dropdown__button">Развернуть/Свернуть</button>
</div>
document.addEventListener('click', e => {
if( !e.target.closest('.dropdown__button') ) return;
const dropdown = e.target.closest('.dropdown');
const dropdownContent = dropdown.querySelector('.dropdown__content');
const dropdownButton = e.target.closest('.dropdown__button');
const opened = (dropdown.getAttribute('aria-expanded') === 'true');
if(opened) {
dropdown.setAttribute('aria-expanded', false);
dropdownContent.style.maxHeight = dropdown.dataset.height + 'px';
} else {
dropdown.setAttribute('aria-expanded', true);
dropdownContent.style.maxHeight = calcHeightContent(dropdownContent) + 'px';
}
})
function calcHeightContent(element) {
const containerClone = element.cloneNode(true);
let naturalHeight = 0;
containerClone.style.position = 'absolute';
containerClone.style.visibility = 'hidden';
containerClone.style.opacity = 0;
containerClone.style.maxHeight = '100%';
containerClone.style.zIndex = -1;
element.parentNode.append(containerClone);
naturalHeight = containerClone.clientHeight;
containerClone.remove();
return naturalHeight;
}
Answer the question
In order to leave comments, you need to log in
When expanding, look at the height of the scrollHeight block, animate the expansion. Then set the height to auto. On close, set the height to scrollHeight and animate the shrink.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question