
How it works
The button listens for one click and calls window.scrollTo with top set to 0. The behavior option chooses smooth scrolling, while left remains unchanged.
Example
Replace window.scrollTo with document.querySelector("#content").scrollIntoView({ behavior: "smooth" }) to scroll to a named section instead of the page top.
HTML & CSS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 8rem;
}
.fe{
background: rgb(255, 54, 54);
}
.se{
background: rgb(60, 60, 255);
}
.th{
background: rgb(255, 60, 219);
}
.fo{
background: rgb(129, 57, 252);
}
.btn{
position: fixed;
bottom: 20px;
right: 20px;
width: 50px;
height: 50px;
font-size: 2rem;
background-color: black;
color: white;
border-radius: 50px;
border: none;
cursor: pointer;
outline: none;
transition: all 0.4s;
}
.btn:hover{
height: 80px;
}
</style>
<div class="fe">1</div>
<div class="se">2</div>
<div class="th">3</div>
<div class="fo">4</div>
<button class="btn"><i class="fa fa-arrow-up"></i></button>JS Code:
1
2
3
4
5
6
7
8
9
const btn = document.querySelector('.btn');
btn.addEventListener('click', () => {
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
});
});
Expected output
Clicking the fixed circular arrow immediately begins an animated scroll to the top of the four full-height demo sections.
