Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

JavaScript - scroll to top page after page refresh

0 contributions
3 points

 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);.

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey ūüĎč
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more