Dropdown/Accordion Behavior

Hi Nathan,

Fiza has the right idea- but the main issue is that you are collapsing all other accordion dropdowns when you open the new one.

This creates a side effect- if you open item #2, then scroll down and open #3, item #2 collapses which brings the start of #3 upward and off-screen.

So two easy solutions-

1 - Don’t collapse your items, only open/close on user click. That will sidestep your UX issue.
2 - Custom code to reposition the item.

Fiza, you can easily drop in code here with markdown, just use three backticks ``` before and after your code.

Nathan, you can put this in the before-/body custom code area. It will target any element with the class accordion-toggle.

<script>
const accordionToggles = document.querySelectorAll('.accordion-toggle');
accordionToggles.forEach(toggle => {
  toggle.addEventListener('click', () => {
    // Wait half a second (500ms) before scrolling
    setTimeout(() => {
      const offset = 200; // Distance from the top in px
      const elementTop = toggle.getBoundingClientRect().top + window.pageYOffset;

      // Scroll to the element
      window.scrollTo({
        top: elementTop - offset,
        behavior: 'smooth' 
      });
    }, 500);
  });
});
</script>

Notes;

  • I set the scrollTo position to offset of 200px from the top of the page, you can change that in the offset var
  • Since you have an interaction happening, we want the positioning to happen after the interaction completes. I wasn’t sure how long that takes, so I’m delaying half a second before scrolling. You can change that setting it’s the 500 at the end of the setTimeout block.
2 Likes