Avatar ·

Scrolling page to top with JavaScript: simple and reliable solution

Hello everyone! I'm new to JavaScript and can't figure out scrolling the page to the top. On my site there is a long page with content, and I want to make a "Back to Top" button so users can quickly return to the beginning.\n\nI tried using `window.scrollTo(0, 0)` — it seems to work, but it's abrupt, without animation. I want smooth scrolling. I tried to do it via `window.scrollBy()`, but got confused with the logic. I also tried the old method `window.scrollTo({ top: 0, behavior: 'smooth' })`, but it doesn't work in some browsers, especially older versions of Safari.\n\nHere is my current code that I threw together:\n\n
function scrollToTop() {\n  window.scrollTo(0, 0);\n}
\n\nThe button works, but it's jerky. Tell me how to make smooth scrolling that will work in all