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:
xxxxxxxxxx
1
var element = document.querySelector('#element');
2
3
element.scrollTop = element.scrollHeight;
Warning: the
element
should have enabled scrolling with specified height to get the effect.
In this example, we set scrollTop
property of the element
to scrollHeight
to scroll to the bottom of the element.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="height: 80px; overflow-y: auto">
5
<div>Some text here...</div>
6
<div>Some text here...</div>
7
<div>Some text here...</div>
8
<div>Some text here...</div>
9
<div>Some text here...</div>
10
<div>Some text here...</div>
11
<div>Some text here...</div>
12
<div>Some text here...</div>
13
<div>Last line here...</div>
14
</div>
15
<script>
16
17
var element = document.querySelector('#element');
18
19
element.scrollTop = element.scrollHeight;
20
21
</script>
22
</body>
23
</html>
Note: if scrolled element has dynamically loaded content, then you have to set the scroll after they have been loaded.
In this example, we create a button that scrolls to the bottom of the element on click event using the above solution.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="height: 80px; overflow-y: auto">
5
<div>Some text here...</div>
6
<div>Some text here...</div>
7
<div>Some text here...</div>
8
<div>Some text here...</div>
9
<div>Some text here...</div>
10
<div>Some text here...</div>
11
<div>Some text here...</div>
12
<div>Some text here...</div>
13
<div>Last line here...</div>
14
</div>
15
<button onclick="scrollBottom()">Scroll to bottom</button>
16
<script>
17
18
var element = document.querySelector('#element');
19
20
function scrollBottom() {
21
element.scrollTop = element.scrollHeight;
22
}
23
24
</script>
25
</body>
26
</html>