Languages
[Edit]
EN

JavaScript - scroll to top page after page refresh

3 points
Created by:
Root-ssh
174740

In this article, we're going to have a look at how using JavaScript, scroll the page to the top after the refresh operation is performed.

There are 2 good approaches:

  • scroll to top before the page is unloaded (refresh = unload + load),
  • scroll to top page after page is loaded.

1. Scroll to the top before the page is unloaded example

This solution is based on fact, for almost all modern web browsers, the page is loaded after refresh operation with the same scroll bar state that was before the operation. So it is necessary just to reset the position before the page is unloaded.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script>

    window.onbeforeunload = function() {
        window.scrollTo(0, 0);
    };

  </script>
</head>
<body>
  Web page content...
</body>
</html>

2. jQuery scroll to top after document ready example

This solution uses jQuery that after the document is ready, scrolls the page to the top.

Note: main disadvantage of this approach is possible page jumping after is the page is loaded.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
  <script>

    $(document).ready(function(){
        $(this).scrollTop(0);
    });

  </script>
</head>
<body>
  Web page content...
</body>
</html>

Note: $(this).scrollTop(0); can be replaced by $('html, body').scrollTop(110);.

Alternative titles

  1. JavaScript - reset scroll after page reload
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join