Languages
[Edit]
EN

JavaScript - scroll to bottom of element

3 points
Created by:
Niac
478

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>

 

See also

  1. JavaScript - scroll to top of element

References

  1. Element.scrollHeight - Web APIs | MDN

Alternative titles

  1. JavaScript - scroll to bottom of element on click event
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join