scrollToElement with a fixed header
-
Hi,
I’m trying to setup a page with a scrollToElement . I have not really understood how I should prepare the parent. I managed to obtain a scrollToElement correctly working if the div with “scroll” class is the outer div in the content area.
If I have a header (where I place the links that I’d like to stay visible) the scroll has a wrong offset.
I prepared a codesandbox to show the two different situations.
Which is the suggested solution for this kind of layout/request?thanks in advance
Sandro -
I solved this by forcing the offset in the scrollToElement function. I subtract the offsetTop of the element that has the “scroll” class.
So my final working function is:scrollToElement (el) { const target = getScrollTarget(el) const offset = el.offsetTop - target.offsetTop // adjust the scrolling const duration = 100 setScrollPosition(target, offset, duration) }
UPDATE: The adjustment (
- target.offsetTop
) is only needed if the scrollable element is not positioned. In that caseel.offsetTop
is referred to the offsetParent that is the closest positioned ancestor.