Home > Back-end >  How to offset smooth-scroll to account for height of static navbar?
How to offset smooth-scroll to account for height of static navbar?

Time:10-21

I am currently using Bootstrap for my website.

I am using the navbar from Bootstrap, and each of my HTML section tags has an id (ex: #about-section, #contact-section)

This allows me to use anchor tags like href="#about-section" for smooth scrolling to any section.

This works wonderfully, however once I introduced my navbar to be static, whenever I click on a navigation link that is supposed to smooth scroll me to the section, it smooth scrolls but the navbar covers a big portion of the section.

I have seen solutions but that use jQuery. What is the native JS way of doing this?

CodePudding user response:

I can tell you two ways to solve this issue. Way 1 is easy with CSS and way 2 is with javascript.

Way 1: padding-top

Use padding-top to your section. The value of padding-top will the amount of height of the navbar. So when the scroll occurs to that section, actually it will start from the top. But for padding-top you can see the section after the navbar.

Way 2: Javascript

const links = document.querySelectorAll(".nav-link"); // or any other selector what you want

for (const link of links) {
  link.addEventListener("click", scrollToSection);
}

function scrollToSection(e) {
  e.preventDefault();
  const href = this.getAttribute("href");
  const offsetTop = document.querySelector(href).offsetTop;
  const navbarHeight = document.querySelector(".navbar").offsetHeight

  scroll({
    top: offsetTop - navbarHeight,
    behavior: "smooth"
  });
}
  • Related