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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more