DEV Community


Posted on

Scrolling to a specific element on a page

I recently needed to scroll to various elements on a page via Javascript. I wanted to specifically see if there was a better way to do it than manually finding the offset as below

document.getElementsByClassName('series-list')[0].scrollTop = document.getElementsByClassName('breakpoint')[0].offsetTop;
Enter fullscreen mode Exit fullscreen mode

And I found out about Element.scrollIntoView, amazingly all major browsers support it, despite it being a working draft.

So you can simply do

Enter fullscreen mode Exit fullscreen mode

As with Javascript there are numerous ways to accomplish the same thing but I never knew this existed and thought it was worth the share.


Top comments (2)

moopet profile image
Ben Sinclair

One problem with scrollIntoView is that it scrolls the window until the top of the element is inside the viewport, but many sites (like DEV, for example) have a fixed header.
If you try it on an element on this page, then the element will remain partially hidden under the header. You'll end up needing to follow the scrollIntoView call with one to window.scrollBy passing in the height of the header as currently rendered (so reading it from the element rather than CSS)

1e4_ profile image

I don't really call that a problem as you're wanting to do something this function doesn't provide.

But yes it's definitely a gotcha at first if your using fixed/sticky elements 👍