You want to reset the page offset to the top, which means scrolling back to the top of the page. You can do this with JavaScript by using the following code:

window.scrollTo(0, 0);
;

This code uses the window.scrollTo() method, which takes two arguments: the first is the x-coordinate (horizontal position) and the second is the y-coordinate (vertical position). By setting both to 0, the page will scroll back to the top left corner.

Alternatively, you can use:

document.body.scrollTop = 0;

This code sets the scrollTop property of the document.body element to 0, which also scrolls the page back to the top.

We definitely need an event to trigger the above scripts which can be any click event, while page loads or while unloads. Here is an example to scroll to top with unload event.
window.onbeforeunload is an event handler that allows you to execute a function just before the page is unloaded. This event is triggered when the user navigates away from the page, closes the browser, or refreshes the page.

The onbeforeunload event is often used to:

1. Prompt the user to save changes before leaving the page.
2. Cancel the navigation event (e.g., stay on the page).
3. Perform some final tasks, like cleaning up resources or sending analytics data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app"></div>

    <script>
      window.onbeforeunload = function () {
        window.scrollTo(0, 0);
      };
    </script>
  </body>
</html>

   Keep in mind that this event is not supported in all browsers, and its behavior may vary.