Victor Ferreira
Victor Ferreira

Reputation: 6449

Can't force Chrome to Scroll to top of page with Javascript

I have finished developing my website and I am testing it. I run a script after 1 second to check the height of the header/top and add a margin-top to the content section. but this header/top changes sizes depending on the scroll position (on runtime). So first I have to make sure the page scroll is set to (top) 0 and then run this script. Sometimes the user has scrolled down and refreshed, and the natural browser's behavior is to scroll the page to where it was.

After several attempts on Google Chrome and after commenting most of my code that is triggered when page loads, I tried the same on Firefox and it works! So this code doesn't work on Chrome:

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

I used the animate function and passed a callback to alert "Hello" and it alerts on top, then I click "Ok" and it goes back to where the scroll was before the refresh.

I also tried without jQuery and nothing happens

window.scrollTo(0,0);

On Firefox it works fine. No Javascirpt code is running BUT the scrollTop (maybe things like social plugins, but nothing mine).

Does anybody know a workaround or how to fix it? Whats the matter with Chrome?

Upvotes: 1

Views: 6904

Answers (4)

Shaze
Shaze

Reputation: 972

In jQuery:

Just Add this line in the beginning of your document load (Assuming you have jQuery framework parsed on your HTML page):

$(document).ready(function)() {

  $(document.body).animate({scrollTop: '0px'}, 1000);// 1sec animation scroll up
  //Your rest of the code goes below -

});

Upvotes: 0

Priyal Shah
Priyal Shah

Reputation: 1

Try these solution. I hope this will be helpful

$(document).scroll(function() {
        if ($(this).scrollTop() > 100) {

               if(window.innerWidth <= 768){
                        $("html, body").css({ 
                        "position" : 'fixed',
                        "top" : 0 , "margin-left" : 566});
               }else{

                    $("html, body").css({ 
                    "position" : 'fixed',
                    "top" : 0 , "margin-left" : 721});
               }
        } else {
            $("html, body").css({ "position" : 'relative', "margin-left" : 0});
        }
    })

Upvotes: 0

Doug WB
Doug WB

Reputation: 340

Another potential solution:

window.setTimeout(function() {
    window.scrollTo(0,0);
}, 0);

I did have intermittent problems with the above code after refreshing multiple times, until I removed the reference to the Google-hosted jQuery library. It could just be a measure to mitigate abuse from constant refreshing.

There are a bunch of good suggestions here: The same old issue, .scrollTop(0) not working in Chrome & Safari

Upvotes: 1

Rufus
Rufus

Reputation: 171

I'm using Chrome 41 and this works:

$("html, body").animate({
        scrollTop: 0
    }, 9000);  

Upvotes: 1

Related Questions