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>
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
})
Here's the result:
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
})
})
Here's the result:
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)