DEV Community

Ibrahim
Ibrahim

Posted on

2 Ways to Scroll an Element in JavaScript

Suppose there is an overflowing article element and a button to scroll it to the bottom.

<article style="max-width: 200px; max-height: 200px; overflow-y: auto; border: 1px solid">
  <p>Lorem ipsum dolor sit amet...</p>
  <p>Lorem ipsum dolor sit amet...</p>
  <p>Lorem ipsum dolor sit amet...</p>
</article>
<button>Scroll to the Bottom</button>
Enter fullscreen mode Exit fullscreen mode

An Overflowing Article

To make it work, the first way is to set the scrollTop property of the article element to its scrollHeight.

scrollHeight is a property that returns the total height of an element's content.

document.querySelector('button')
  .addEventListener('click', () => {
    const article = document.querySelector('article')

    article.scrollTop = article.scrollHeight
  })
Enter fullscreen mode Exit fullscreen mode

Here's the result:

Scroll to Bottom using scrollTop Property

The second way is to use the scrollTo method. With this method, we can specify the top and left scroll positions, and optionally add scroll animation.

document.querySelector('button')
  .addEventListener('click', () => {
    const article = document.querySelector('article')

    article.scrollTo({
      top: article.scrollHeight,
      left: 0,
      behavior: 'smooth' // animasi scroll
    })
  })
Enter fullscreen mode Exit fullscreen mode

Here's the result:

Scroll to Bottom using scrollTo Method


That's it — the two ways to scroll to a specific position of an overflowing element using JavaScript. Both ways work and provide the same functionality. The scrollTo method alse offers an option to animate the scrolling.

Top comments (0)