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:
xxxxxxxxxx
1
var element = document.querySelector('#element');
2
3
element.scrollTop = 0;
Note: go to this article if you're looking for a solution that works in both modern and older browsers.
In this example, we set scrollTop
property to 0
to scroll to the top of the element on the button click event.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="border: 1px solid silver; height: 80px; overflow-y: auto">
5
<div>Scroll this text to bottom and click the button</div>
6
<div>Line 1</div>
7
<div>Line 2</div>
8
<div>Line 3</div>
9
<div>Line 4</div>
10
<div>Line 5</div>
11
<div>Line 6</div>
12
<div>Line 7</div>
13
<div>Line 8</div>
14
<div>Line 9</div>
15
<div>Line 10</div>
16
</div>
17
<script>
18
19
var element = document.querySelector('#element');
20
21
function scrollToTop() {
22
element.scrollTop = 0;
23
}
24
25
</script>
26
<button onclick="scrollToTop()">Scroll to top</button>
27
</body>
28
</html>
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="border: 1px solid silver; height: 80px; overflow-y: auto">
5
<div>Scroll this text to bottom and click the button</div>
6
<div>Line 1</div>
7
<div>Line 2</div>
8
<div>Line 3</div>
9
<div>Line 4</div>
10
<div>Line 5</div>
11
<div>Line 6</div>
12
<div>Line 7</div>
13
<div>Line 8</div>
14
<div>Line 9</div>
15
<div>Line 10</div>
16
</div>
17
<script>
18
19
var element = document.querySelector('#element');
20
21
function scrollToTop() {
22
element.scroll(element.scrollLeft, 0);
23
24
// or:
25
26
// element.scrollTo(element.scrollLeft, 0);
27
}
28
29
</script>
30
<button onclick="scrollToTop()">Scroll to top</button>
31
</body>
32
</html>
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element" style="border: 1px solid silver; height: 80px; overflow-y: auto">
5
<div>Scroll this text to bottom and click the button</div>
6
<div>Line 1</div>
7
<div>Line 2</div>
8
<div>Line 3</div>
9
<div>Line 4</div>
10
<div>Line 5</div>
11
<div>Line 6</div>
12
<div>Line 7</div>
13
<div>Line 8</div>
14
<div>Line 9</div>
15
<div>Line 10</div>
16
</div>
17
<script>
18
19
var element = document.querySelector('#element');
20
21
function scrollToTop() {
22
element.scroll({
23
top: 0,
24
behavior: 'smooth'
25
});
26
27
// or:
28
29
// element.scrollTo({
30
// top: 0,
31
// behavior: 'smooth'
32
// });
33
}
34
35
</script>
36
<button onclick="scrollToTop()">Scroll to top</button>
37
</body>
38
</html>