Reputation: 333
I have a page which has fixed header. On that page I have a table which has the functionality that when clicked on a row, the page scrolls to that element. Each table row has an id which matches the element's id. So on click, I get the element's id and then execute this function
element.scrollIntoView({block: 'start', behavior: 'smooth'})
The problem with this approach is the scroll goes too far and some portion of the element is hidden underneath the fixed header. I looked at lot of solutions on stack overflow but none of them worked for me. I want the scroll to end at the element top.
So, I then tried using
element.scrollTo({top: element.offsetTop, behavior: 'smooth})
I did some calculations like considering padding/margin and got it to work. The problem is the offsetTop is different on different device. The above logic doesn't work for mobile and tablet. the offsetTop is distance of the current element relative to the top of the offsetParent which will not be the same for each device.
I know that scrollIntoView
will be my best bet but not sure how to prevent the element from scrolling underneath the fixed header. Any help is appreciated.
Upvotes: 0
Views: 938
Reputation: 1
const fixedHeaderHeight = /* height in pixels */;
const element = /* your element */;
const adjustedScrollTop = element.offsetTop - fixedHeaderHeight;
element.scrollIntoView({ block: 'start', behavior: 'smooth' });
Upvotes: 0
Reputation: 1163
I've tested and researched a little bit and maybe this is what you need.
const position = element.getBoundingClientRect().top + window.pageYOffset - header.clientHeight;
window.scrollTo({ top: position, behavior: 'smooth'});
Upvotes: 0