Jumping page scroll when closing accordion

48 views Asked by At

I have an accordion written in JS + SCSS. Here's how it works:

  1. When you open an accordion, another active accordion is automatically closed
  2. opening/closing of the accordion is smooth, animated
  3. There can be a lot of content in one accordion

Problem: When I open an accordion, the other active accordion automatically closes. When it closes, my page "jumps", scrolling is glitched. I assume this is due to the page content height changing at the top, and all the content at the bottom being pulled up.

Code: here is piece of my code, so you can understand how it works:

if (dropdownHeader) {
    if (!dropdown.classList.contains('process__item_active')) {
        closeAllItems()
        dropdown.classList.add('process__item_active')
        content.style.maxHeight = content.scrollHeight + 'px'
    } else {
        dropdown.classList.remove('process__item_active')
        content.style.maxHeight = 0
    }
}

    function closeAllItems() {
      accItems.forEach((item) => {
        item.classList.remove('process__item_active')
        item.querySelector('.process__item-wrapper').style.maxHeight = 0
      })
    }

I tried to solve this with an automatic scroll to open accordion, but it looked crooked: first the scroll would bunch up, then it would pull up to the accordion at the top. It looks like a roller coaster.

I also tried to find other working accordions on the internet that might solve my problem. But none of them are up to the task. Maybe scroll to accordion is the only solution. Then I need to make the scroll without the page jerking down so it all looks neat and convenient.

Question: how can I write an accordion with automatic closing of another one so that the content doesn't jump? How to solve my problem? Thanks in advance.

0

There are 0 answers