0

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.

pogbamessi
  • 311
  • 3
  • 17
  • I had similar issues because of the url bar on mobile. A non-perfect way of resolving the issue is just call the scrollTo method one more time after the first one finishes. Not sure but it may help you. – dako Mar 11 '20 at 21:04
  • The problem with using scrollTo is the `offsetTop` is different on each device. Even if add a second scrollTo method it might work on Desktop but not work on others. – pogbamessi Mar 11 '20 at 21:06

1 Answers1

0

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'});
dako
  • 1,081
  • 1
  • 12
  • 22