Skip to content
pbb.io/blog

TIL how to scroll elements into view with JavaScript

February 1, 2025
1 min read
JavaScript

Element.scrollIntoView() scrolls an element’s parent container so that the element becomes visible. Passing false aligns the element to the bottom of the scrollable area, which is perfect for keeping a selected item in view when navigating a list with arrow keys.

I used this on my blog’s search component. When the user presses arrow keys, Phoenix LiveView pushes an event to the client, which then scrolls the active result into view:

window.addEventListener("phx:search-choose", (e) => {
const activeItem = this.el.querySelector(".menu-active")
activeItem.scrollIntoView(false)
})

The argument controls alignment:

  • true (default): aligns to the top of the scrollable area
  • false: aligns to the bottom
  • An object for more control: { behavior: "smooth", block: "nearest" }

Back to posts

JavaScript
Phil-Bastian Berndt

Phil-Bastian Berndt
Tech Lead at Naymspace