Languages
[Edit]
EN

JavaScript - scroll to top page after page refresh

3 points
Created by:
Root-ssh
68570

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

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join