I have a scroll to top button fixed at the bottom-right of my page. When it’s clicked, all I want is to scroll top of the page.
Now, What I tried:
window.scrollTo(0,0)
window.scroll({
top: 0,
left: 0,
})
document.body.scrollTop = 0
document.documentElement.scrollTop = 0
document.querySelector('header').scrollIntoView({
behavior: "smooth", block: "start", inline: "nearest"
})
all of these works at first but as I scroll down, they scroll up the page a little bit and then stop. they don’t go up.
Why might it be?
PS: I use chrome
2
Answers
Based on @dkellner 's comment I thought that it might related to smooth behavior,
When I searched it through my css code I found out that I had this line:
I changed it to
and problem is solved.
I know giving all elements scroll-behavior: smooth don't make sense but I really like to know why it causes such an issue.
Use JavaScript to smoothly scroll to the top of the page when the "scroll to top" button is clicked. To prevent interference with the fixed button’s positioning, you can temporarily disable the button’s position: fixed property while scrolling, and then re-enable it afterward.