Languages
[Edit]
EN

JavaScript - safe way to scroll top of element

0 points
Created by:
chelsea
806

In this article, we would like to show you a safe way to scroll to the top of an element using JavaScript.

Practical example

This approach will work for any web browser. In older browsers, it will jump to the top immediately and in newer browsers, it will go smoothly.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="element" style="border: 1px solid silver; height: 80px; overflow-y: auto">
    <div>Scroll this text to bottom and click the button</div>
    <div>Line 1</div>
    <div>Line 2</div>
    <div>Line 3</div>
    <div>Line 4</div>
    <div>Line 5</div>
    <div>Line 6</div>
    <div>Line 7</div>
    <div>Line 8</div>
    <div>Line 9</div>
    <div>Line 10</div>
  </div>
  <script>

    var element = document.querySelector('#element');

    function scrollToTop() {
        if ('scroll' in element) {
            element.scroll({
                top: 0,
                behavior: 'smooth'
            });
        } else {
            element.scrollTop = 0;
        }
    }

  </script>
  <button onclick="scrollToTop()">Scroll to top</button>
</body>
</html>

See also

  1. JavaScript - scroll to top of element

Alternative titles

  1. JavaScript - scroll top of element (with legacy)
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