May 17, 2022
White Arrow icon
Back to all Elements

Scroll Menu to Current Link

Using JS to scroll a div (menu) to the current link inside.

I see more and more designs with side scroll menus, so I figured we need a component that automatically scrolls the menu to our current link.

Our structure needs to be:

  • The "scrollable" DIV with overflow:auto, display:flex. This item needs an ID of 'scrollMenu'.
  • Inside the scrollable DIV we add all the links. Those can be static text-links elements, or dynamic list with a text-link in each item.

Our code waits for the page to load, and then checks for the current link's offset from the left, and then scrolls the menu in that amount. I added 20px padding for the menu, thus the "-20px"

Add this code to every page the menu appears on, at the page settings section "Before </body> tag"

<script>
 window.addEventListener('DOMContentLoaded', (event) => {

   const scrollDiv = document.getElementById('scrollMenu');
   const links = document.querySelectorAll('.link.w--current');
   const currentLink = links[0];
   const currentLinkOffset = links[0].offsetLeft - 20;
   
   scrollDiv.scrollLeft = currentLinkOffset;
 });
</script>

Copy

Preview:

browser mockup
Share:
Heart icon

The videos Kurzgesagt channel creates are so beautifully animated, that I almost forget that I learn so much while watching them!

Might also interest you:

Scaleable Vanilla JS Nested Tabs

JavaScript
Cloneable
Code

Nested tabs in an accordion template

Read more
Blue arrow iconWhite Arrow icon

Buttons Hover Interactions

Cloneable
Interactions

A small collection of buttons and hover interactions.

Read more
Blue arrow iconWhite Arrow icon

3d Video Slider (swiper.js)

Cloneable
CMS
JavaScript

A 3d slider with video items, plays and pauses on click & slide change.

Read more
Blue arrow iconWhite Arrow icon