Slater New

How to Fix Anchor Link Scroll Position with a Fixed Navbar in Webflow or Slater

When using a fixed navigation bar on your site, clicking anchor links can cause the target section to appear hidden behind the navbar. This is a common issue with fixed headers in Webflow and Slater projects. The following JavaScript solution adjusts the scroll position to account for your navbar's height, resulting in a seamless user experience.


Step-by-Step Instructions

1. Copy the JavaScript Code

Paste the following script into your project. This code ensures that anchor links scroll to the correct position, offsetting for the fixed navbar height.

// Smooth scroll with offset for fixed navbardocument.querySelectorAll('a[href^="#"]').forEach(anchor => {  anchor.addEventListener('click', function(e) {    const navbarHeight = 80; // Change this to match your navbar's height in px    const targetId = this.getAttribute('href').slice(1);    const targetElement = document.getElementById(targetId);    if (targetElement) {      e.preventDefault();      const elementPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;      window.scrollTo({        top: elementPosition - navbarHeight,        behavior: 'smooth'      });    }  });});

2. Add the Code to Your Project

  • Paste the code directly into your Slater project.

3. Adjust the Navbar Height

Update the navbarHeight variable in the script to match the exact height (in pixels) of your fixed navbar (e.g., use 80 for an 80px tall navbar).


Example

If your navbar is 60px tall, set:

const navbarHeight = 60;

Troubleshooting

  • Ensure the anchor links use the correct href attribute (e.g., #section1).
  • Verify the navbar height matches your design for accurate scrolling.
  • Test on multiple devices and browsers for consistent behavior.

Additional Resources

For more guidance, see the resources above for official tutorials and documentation.

Jared Malan