Link & Anchor in Menu component?

So many dev diaries…so many releases! This is a crazy (but fun) ride!

Sorry if I missed it, but is there (or will there be) a way to have links (to anchors) in the menu component? Obvious main reason being a one-page site.

Thanks, and keep up the great work @dan and the Elements team!

1 Like

@miketee You can already do this with the “link pages”. Hope the graphic below makes sense :

2 Likes

If you want to get fancy, you can control the speed the links scroll to there targets adding this to the page > body end.

<script>
  function smoothScrollTo(target, duration = 1500) {
    const targetPosition = target.getBoundingClientRect().top + window.scrollY;
    const startPosition = window.scrollY;
    const distance = targetPosition - startPosition;
    const startTime = performance.now();

    function animation(currentTime) {
      const timeElapsed = currentTime - startTime;
      const progress = Math.min(timeElapsed / duration, 1);

      // easeInOutQuad easing
      const easedProgress = progress < 0.5
        ? 2 * progress * progress
        : -1 + (4 - 2 * progress) * progress;

      window.scrollTo(0, startPosition + distance * easedProgress);

      if (timeElapsed < duration) {
        requestAnimationFrame(animation);
      }
    }

    requestAnimationFrame(animation);
  }

  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
      e.preventDefault();
      const target = document.querySelector(this.getAttribute('href'));
      if (target) {
        smoothScrollTo(target, 1500); // duration in ms (e.g., 1500 = 1.5 seconds)
      }
    });
  });
</script>

Thanks! I suspected it was something like above.

That said…it would be nice to have some of this functionality baked right into the Menu component, no? :wink:

The basic functionality (forgetting the extra JS,) is pretty well baked in as is. And by default you do get a smooth scroll to the target without any extra JS. That was just me pushing the boundaries.

1 Like

Yeah…as one of the “non-devs” in here, I’m probably missing a lot! :stuck_out_tongue:

I’d TOTALLY welcome a pre-built menu component designed for one-page sites!

Thanks again for chiming in and sharing some tips :slight_smile:

Templates will help with this — We’ll be providing dozens of pre-built collections of components for all kinds of site layouts (including menus). Stay tuned for that soon!

1 Like

I figured as much! Thanks @dan !