you can do this step by step:
- find the element to scroll into view
- calculate the element's scroll position from top
- calculate the height of the navbar
- 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);
}
}