DEV Community

Ian
Ian

Posted on

3

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

document.getElementsByClassName('series-list')[0].scrollIntoView()
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.

mdn

Top comments (2)

Collapse
 
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)

Collapse
 
1e4_ profile image
Ian

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 👍

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay