Sometimes, we want to use scrollIntoView with a fixed position header with JavaScript.
In this article, we’ll look at how to use scrollIntoView with a fixed position header with JavaScript.
How to use scrollIntoView with a fixed position header with JavaScript?
To use scrollIntoView with a fixed position header with JavaScript, we can call scroll
to scroll to the element at the given position.
For instance, we write
const node = document.getElementById("foo");
const yourHeight = 200;
node.scrollIntoView(true);
const scrolledY = window.scrollY;
if (scrolledY) {
window.scroll(0, scrolledY - yourHeight);
}
to select the element we want to scroll to with getElementById
.
Then we call node.scrollIntoView
to scroll to the element.
Next, we call window.scroll
to to scroll to scrolledY - yourHeight
to scroll to the given position.
Conclusion
To use scrollIntoView with a fixed position header with JavaScript, we can call scroll
to scroll to the element at the given position.