EN
JavaScript - scroll to top of element
6
points
In this article, we would like to show you how to scroll to the top of an element using JavaScript.
Quick solution:
var element = document.querySelector('#element');
element.scrollTop = 0;
Note: go to this article if you're looking for a solution that works in both modern and older browsers.
Using scrollTop
property
In this example, we set scrollTop
property to 0
to scroll to the top of the element on the button click event.
// 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() {
element.scrollTop = 0;
}
</script>
<button onclick="scrollToTop()">Scroll to top</button>
</body>
</html>
Using scroll()
/ scrollTo()
method
In this example, we use scroll()
/ scrollTo()
methods to scroll to the top of the element on button click event.
Note:
scroll()
/scrollTo()
methods appeared in major web browsers around 2015-2020.
// 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() {
element.scroll(element.scrollLeft, 0);
// or:
// element.scrollTo(element.scrollLeft, 0);
}
</script>
<button onclick="scrollToTop()">Scroll to top</button>
</body>
</html>
Smooth scroll behavior
In this example, we use scroll()
/ scrollTo()
methods with smooth
behavior to scroll to the top of the element on button click event.
Note:
scroll()
/scrollTo()
methods appeared in major web browsers around 2015-2020.
// 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() {
element.scroll({
top: 0,
behavior: 'smooth'
});
// or:
// element.scrollTo({
// top: 0,
// behavior: 'smooth'
// });
}
</script>
<button onclick="scrollToTop()">Scroll to top</button>
</body>
</html>