To scroll to the top of the page using JavaScript, you can use the scrollTo() method of the window object. This method takes two arguments: the x-coordinate and the y-coordinate of the element to scroll to. By setting both of these arguments to 0, you can scroll to the top-left corner of the page. Here’s an example:
window.scrollTo(0, 0);
If you want to animate the scroll, you can use the scrollTo() method in combination with the window.requestAnimationFrame() method, which allows you to perform an animation by specifying a callback function to be executed before the next repaint. Here’s an example:
function scrollToTop() {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
scrollToTop();
