EN
JavaScript - scroll to bottom of element
3
points
In this article, we would like to show you how to scroll to the bottom of an element using JavaScript.
Quick solution:
var element = document.querySelector('#element');
element.scrollTop = element.scrollHeight;
Warning: the
element
should have enabled scrolling with specified height to get the effect.
Practical example
In this example, we set scrollTop
property of the element
to scrollHeight
to scroll to the bottom of the element.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="element" style="height: 80px; overflow-y: auto">
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Last line here...</div>
</div>
<script>
var element = document.querySelector('#element');
element.scrollTop = element.scrollHeight;
</script>
</body>
</html>
Note: if scrolled element has dynamically loaded content, then you have to set the scroll after they have been loaded.
Scroll to the bottom on click
In this example, we create a button that scrolls to the bottom of the element on click event using the above solution.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="element" style="height: 80px; overflow-y: auto">
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Some text here...</div>
<div>Last line here...</div>
</div>
<button onclick="scrollBottom()">Scroll to bottom</button>
<script>
var element = document.querySelector('#element');
function scrollBottom() {
element.scrollTop = element.scrollHeight;
}
</script>
</body>
</html>