8

I thought when you clicked refresh, that the browser was supposed to reset your page to the top? I am using a js accordion and when I refresh, it closes the accordion but does not reposition the page to the top.

http://imip.rvadv.com/index3.html

imakeitpretty
  • 2,098
  • 5
  • 14
  • 16

4 Answers4

12

Well, as you can see, it does not :)

But you can force it with some simple jQuery:

$(document).ready(function(){
    $(this).scrollTop(0);
});

EDIT:

The only way that seems to work in IE 9, FF 12 and Chrome 20.0 is the following:

$(document).ready(function(){
    $('html').animate({scrollTop:0}, 1);
    $('body').animate({scrollTop:0}, 1);
});

Strange thing is that when I tried scrolling the elements directly without applying any animation (that is, $('html').scrollTop(0)), it didn't work. Since the duration is set to 1 millisecond, the user will not notice anything.

I would be glad if anyone could shed some light on this - why does the scrolling only work with animations?

Nikola Anusev
  • 6,448
  • 1
  • 26
  • 46
  • In IE9, I am still seeing it jump. It jumps up to the top, then it jumps back down to where it was to begin with. I'd love to see something a little smoother. A slide to top would be nice since thats what the rest of my accordion does. – imakeitpretty Jul 14 '12 at 21:16
  • 2
    It seems to me in chrome, the 'autoscroll' happens on load, not on 'ready'. – commonpike Feb 26 '14 at 12:43
  • 1
    And even onload, i have to add it to the event queu to interrupt the browser behaviour. You can add it to the event queu by using `setTimeout(...,0)`. This may be what your animate() does, too. So `$(window).on('load',function() {setTimeout(function () { $('html,body').scrollTop(0) },0); });` – commonpike Feb 26 '14 at 12:44
11

Try this if none of the above worked. This will trick the browser to think it was at the top of the document before refresh.

$(window).on('beforeunload', function() {
   $(window).scrollTop(0);
});
Nikhil Nanjappa
  • 5,983
  • 2
  • 22
  • 39
6

The browser will scroll down to where you were before the reload, as an attempt at convenience. It's only really useful for excessively long pages.

You can "fix" this like so:

window.onload = function() {document.body.scrollTop = document.documentElement.scrollTop = 0;};
Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
  • This works in FF but not in Chrome and in IE it acts jacked up. The screen kind of flickers before it executes it correctly. – imakeitpretty Jul 14 '12 at 19:53
3

Based on last comment by comonpyke and own tests I recommend

$(document).ready(function(){
    $('html, body').scrollTop(0);

    $(window).on('load', function() {
    setTimeout(function(){
        $('html, body').scrollTop(0);
    }, 0);
 });
});
  • First scrollTop scrolls early
    • after document ready
  • Second scrollTop scrolls late
    • after load event
      • and after timeout