0

I have a web with a fixed navbar menu.

I want to make a scrolling function to a specific element, so if click a menu, it should scroll to that element.

Actually, it's working when I use scrollToView(), but because scrollToView() will scroll element to top of 0, so some of the element is behind the navbar.

How to specify the top of the element, so that the element scrolls under the navbar.

1
  • Please include the relevant code in your question... Commented Mar 14, 2021 at 8:23

2 Answers 2

3

On modern browser you could obtain the same behaviour with CSS only using the scroll-margin-top property and a link to an anchor.

When you click on the link the page will scroll until the #section-1 block, but thanks to the scroll-margin-top property you will define some margin above the element only on scroll, so the section will be visible just below the fixed header. Of course this requires to know in advance the height of the fixed element.

html {
   scroll-behavior: smooth;
   --headerheight: 80px;
}

header {
  position:  fixed;
  top: 0;
  width: 100%;
  height: var(--headerheight);  /* e.g. 80px */
  background: #9bc;
}

section {
  /* e.g. 85px */
  scroll-margin-top: calc(var(--headerheight) + 5px);
  height: 100vh;
  color: #333;
}

header + section { 
  padding-top: calc(var(--headerheight) + 5px); 
}
<main>
   
   <header>Fixed Header</header>
   
   <section id="home">
      <a href="#section-1">Scroll to section 1</a>
   </section>
   
   <section id="section-1" >
      section 1 <br/>
      <a href="#home">Scroll up</a>
   </section> 
   
</main>

Sign up to request clarification or add additional context in comments.

Comments

1

you can do this step by step:

  1. find the element to scroll into view
  2. calculate the element's scroll position from top
  3. calculate the height of the navbar
  4. scroll to the required position

.

const el = document.getElementById("idOfTheElement"); // step 1
const elFromTop = el.offsetTop; // step 2
const navBarHeight = 60; // step 3 (considering it is of fixed height)
window.scrollTo(0, elFromTop - navBarHeight); // step 4

Here i've considered the navbar to be of fixed height. If the height of navbar is dynamic, you'll have to calculate the height using el.offsetHeight.

window.scrollTo will scroll the element without any animation. For smooth scroll use:

el.scrollTo({
  top: x,
  left: y,
  behavior: "smooth"
});

but the above function has browser incompatibility. What I usually do is create a custom function and use that:

function smoothScroll(x, y, el = window) {
  try {
    el.scrollTo({
      top: x,
      left: y,
      behavior: "smooth"
    });
  } catch (e) {
    el.scrollTo(x, y);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.