Dropdown/Accordion Behavior

I followed a tutorial from Webflow on creating an accordion menu and it works great. However when each parent item is clicked, the menu expands so that the top items are not initially visible. When they are clicked, they do not stay at the top of the dropdown options. How can I fix this? Link: Our Communities | Twenty20 Management


Here is my site Read-Only: LINK
(how to share your site Read-Only link)

The issue you’re facing occurs because the accordion expands downward, pushing content below it, and the page doesn’t automatically scroll to keep the clicked item visible. To fix this, you can add a bit of custom code to scroll the clicked accordion item into view whenever it is expanded. If you face any issues in the coding part will be happy to assist you with that.

Thank you for the reply. I do not know what that code would need to be. Can you advise?

sure would help you with that can you provide me an email where I can connect with you.

I would rather not put my email address out there. Could you provide the code here in a reply?

i can provide you mine you can connect there providing code here is a little problematic (fiza.astrosia@gmail.com)

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