Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Refresh 'Jump' with Javascript

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 to prevent this?

I have looked at two options and neither are consistent across Webkit / Firefox.

    window.scrollTo(0, 1);
    $('html, body').animate({ scrollTop: 0 }, 0);

Any ideas?

You can check a google search result for an example.

like image 810
Mark Davidson Avatar asked Mar 04 '12 01:03

Mark Davidson


People also ask

How do I stop a JavaScript page from refreshing?

$(window). on('popstate', function(event) { return true; }); and then send the user to the page that you want to prevent URL Reload, passing the boolean value returned by this function.

How do I stop submit from refreshing?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

Can we disable browser refresh button?

unbind("keydown", disableF5); /* OR jQuery >= 1.7 */ $(document). off("keydown", disableF5); On a side note: This only disables the f5 button on the keyboard. To truly disable refresh you must use a server side script to check for page state changes.

How do I stop HTML page from refreshing?

Click the Start button, type “internet options” and select Internet Options in the search results. In the Internet Properties window, click “Custom tab -> Custom level,” then in the Security Settings window, scroll down until you find “Allow META REFRESH.” Disable this option and click OK.


3 Answers

Works for me:

// Scroll top bro
window.onload = function() {
 setTimeout (function () {
  scrollTo(0,0);
 }, 0);
}
like image 159
Marek Fajkus Avatar answered Oct 21 '22 22:10

Marek Fajkus


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.

like image 28
josetapadas Avatar answered Oct 21 '22 22:10

josetapadas


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>
like image 6
adeneo Avatar answered Oct 21 '22 23:10

adeneo