I have this code for my website:
function clickMe() {
var element = document.getElementById('about');
element.scrollIntoView({
block: 'start',
behavior: 'smooth',
});
}
This works pretty nice but I have a fixed header so when the code scrolls to the element the header is in the way.
Is there a way to have an offset and make it scroll smoothly?
Yes, but not with scrollIntoView()
The scrollIntoViewOptions of Element.scrollIntoView() do not allow you to use an offset. It is solely useful when you want to scroll to the exact position of the element.
You can however use Window.scrollTo() with options to both scroll to an offset position and to do so smoothly.
If you have a header with a height of
30px
for example you might do the following:This will smoothly scroll to your element just so that it is not blocked from view by your header.
Note: You substract the offset because you want to stop before you scroll your header over your element.
See it in action
You can compare both options in the snippet below.