Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent automatic browser scroll on refresh

If you go to a page a and scroll around then refresh the page will refresh at the spot where you left it. This is great, however this also occurs on pages where there is a anchor location in the url. An example would be if you clicked on a link http://example.com/post/244#comment5 and refreshed the page after looking around you would not be at the anchor and the page jumps around. Is there any way to prevent this with javascript? So that no-matter-what you would always navigate to the anchor.

like image 926
ThomasReggi Avatar asked Aug 12 '11 03:08

ThomasReggi


People also ask

How do I stop Web pages from automatically scrolling?

Disable in the browser: go to chrome://flags/#enable-scroll-anchoring and set "Scroll anchoring" to "Disabled".

How do I stop chrome from scrolling automatically?

If you open the Chrome Dev Console (CTRL-Shift-J), you can run the code from there and confirm that it works. It disables AutoScroll, but still allows the middle mouse button to be used to open links in new tabs and close open tabs. The code stops working if you leave the page you run it on.

Why does my Web page scroll down automatically?

Make sure your mouse cable isn't damaged. If you're using a wireless mouse, check or change your batteries. Make sure there's no dirt blocking your scroll wheel. If a controller is plugged in at the same time as your mouse, unplug it.

How do I stop auto scrolling in CSS?

Disabling scroll with only CSS. There's another way to disable scrolling that is commonly used when opening modals or scrollable floating elements. And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.


2 Answers

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 95
josetapadas Avatar answered Sep 20 '22 19:09

josetapadas


To disable automatic scroll restoration just add this tag to head section.

<script>history.scrollRestoration = "manual"</script> 

It's not supported by IE. Browser compatibility.

like image 36
imos Avatar answered Sep 19 '22 19:09

imos