Categories
JavaScript Answers

How to use scrollIntoView with a fixed position header with JavaScript?

Spread the love

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.scrollto 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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.