Languages
[Edit]
EN

JavaScript - scroll to top page after page refresh

3 points
Created by:
Root-ssh
6266

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

There are 2 good aproaches:

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

1. Scroll to top before page is unloaded example

This solution is based on fact, for almost all modern web browsers, page is loaded after refresh operation with same scroll bar state that was before the operation. So it is necessary just to reset position before 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 document is ready scrolls page to 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);.

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍