DEV Community

Brandon Weaver
Brandon Weaver

Posted on

2

Scrolling to Elements with JavaScript

There are a few different ways to scroll to an element using JavaScript.

One way is to simply use element.scrollIntoView(); the other is to use container.scroll() or container.scrollTo(); there's no difference between these two methods from my understanding.

With element.scrollIntoView(), each scroll bar will be used to reach the element we call the method on; this is the simplest solution, however, we don't always want to use every scroll bar.

With container.scroll() or container.scrollTo(), we can pass optional arguments to determine where precisely we want the containing element (the scrollable element) to scroll to.

Below is an example which uses container.scrollTo() to scroll to various elements on the page. Using element.scrollIntoView() in this scenario will cause the scroll bar of the blog post to scroll in conjunction with the scroll bar of the embedded CodePen to reach each element.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay