EN
JavaScript - scroll to top page after page refresh
3
points
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);
.