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)