I have a site with a header set to position: fixed
. On one of my pages, I use scrollIntoView(true)
on an element. My problem is that when scr
Try the following. It works well for me:
const headerHeight = 50; /* PUT HEADER HEIGHT HERE */
const buffer = 25; /* MAY NOT BE NEEDED */
const scrollToEl = document.querySelector("#YOUR-ELEMENT-SELECTOR");
const topOfElement = window.pageYOffset + scrollToEl.getBoundingClientRect().top - headerHeight - buffer;
window.scroll({ top: topOfElement, behavior: "smooth" });
The following code yields a smooth scroll to the top of the element with an offset for fixed header:
var topOfElement = document.querySelector('#targetElement').offsetTop - XX;
window.scroll({ top: topOfElement, behavior: "smooth" });
Where XX is the height of your fixed header.