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.
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' }); } });});
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).
If your navbar is 60px tall, set:
const navbarHeight = 60;
href
attribute (e.g., #section1
).For more guidance, see the resources above for official tutorials and documentation.