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.

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

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

Okay