Awais Umar
Awais Umar

Reputation: 2075

Chrome/Safari - window.scroll on page load

I am working on a project where my client is asking to load the page on the top. Here is the requirment

Whenever you refresh the page, no matter where you are in browsing, the page must refresh at the top of the page.

To get this, I used two functions window.scroll(0,0) and scrollTop(0) at document load.

 jQuery(document).ready(function(e){
  window.scroll(0,0);
 });

And

 jQuery(document).ready(function(e){
  jQuery("body,html,document").scrollTop(0);
 });

I get the desired results in browsers using any of the above two codes except in Chrome/Safari.
This is what I am experiencing in Chrome/Safari. Let's say that I am at the bottom of a page, then if I refresh it, then I get the events in the following sequence.

  1. Page loads at the point where I was at the time of refresh. (Bottom - Page loading).
  2. Then the functions mentioned above work and get me to the top of the page. (Still loading).
  3. At last, when the page fully loads, it takes me back to where I was at the time of refreshing the page i.e. at the bottom.

You can check it at this page.

I have also tried to put a timeout function as.

 jQuery(document).ready(function(e){
  setTimeout(function() {window.scrollTo(0, 0);},500)
 });

Now, this works one some pages but not on all. So I am looking for a better way than mine. Thank you.

Upvotes: 0

Views: 1305

Answers (1)

Tom
Tom

Reputation: 48

You should use something like this:

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

Edit: Chrome/safari:

$(window).on('beforeunload', function() {
    $(window).scrollTop(0);
});

Upvotes: 1

Related Questions