I\'ve noticed that if you are on a page and you have scrolled down a good bit, if you refresh the page, most browsers will jump you back down to your position. Is there any way
I see no reason why this shouldn't work in all browsers, seems to work for me (with only one function for window.onload, use more and there could be problems) ?
window.onload = function() {
scrollTo(0,0);
}
To make it work when back button is clicked aswell, maybe something like this:
<body onunload="">
<script type="text/javascript">
window.onload = function() {
scrollTo(0,0);
}
</script>
//content here
</body>
Works for me:
// Scroll top bro
window.onload = function() {
setTimeout (function () {
scrollTo(0,0);
}, 0);
}
Something like below works for me, create some item that can be focused and focus it to scroll page.
In this case it will scroll back to top after refresh the page.
Tested on latest IE/FF/Chrome.
<html>
<head>
<script type="text/javascript">
window.onload = function () {
setTimeout (function () {
// use both 'a' and 'button' because 'a' not work as expected on some browsers
document.getElementById('top_anchor').focus();
document.getElementById('top_anchor_btn').focus();
}, 0);
}
</script>
</head>
<body>
<a id="top_anchor" href="" style="width: 1px; height: 1px; position: absolute; top: 0px; left: -1000px;"></a>
<button id="top_anchor_btn" href="" style="width: 1px; height: 1px; position: absolute; top: 0px; left: -1000px;"></button>
<div> top </div>
<div style="width: 500px; height: 2000px; background-color: #83FEBC;">
content
</div>
</body>
</html>
Regards,
Ben
Just to update what @josetapadas said, for recent versions it would be better to use the unload
function instead of beforeunload
this will be
$(window).on('unload', function() {
$(window).scrollTop(0);
});
On Chrome, even if you force scrollTop to 0 it will jump afterwards after the first scroll event.
You should bind the scroll to this:
$(window).on('beforeunload', function() {
$(window).scrollTop(0);
});
So the browser is tricked to believe that it was on the beginning before the refresh.