Search code examples
javascriptjqueryhtmlscroll

How to scroll to top of page with JavaScript/jQuery?


Is there a way to control browser scrolling with JavaScript/jQuery?

When I scroll my page half way down, then trigger a reload, I want the page to go pack to the top, but instead it tries to find the last scroll position. So I did this:

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

But no luck.

EDIT:

So both your answers worked when I call them after the page loads-Thanks. However, if I just do a refresh on the page, looks like the browser calculates and scrolls to its old scroll position AFTER the .ready event (I tested the body onload() function too).

So the follow up is, is there a way to PREVENT the browser scrolling to its past position, or to re-scroll to the top AFTER it does its thing?


Solution

  • Wow, I'm 9 years late to this question. Here you go:

    Add this code to your onload.

    // This prevents the page from scrolling down to where it was previously.
    if ('scrollRestoration' in history) {
        history.scrollRestoration = 'manual';
    }
    // This is needed if the user scrolls down during page load and you want to make sure the page is scrolled to the top once it's fully loaded. This has Cross-browser support.
    window.scrollTo(0,0);
    

    To run it on window load just put it wrap it like this (assumes you have JQuery referenced)

    $(function() {
      // put the code here
    });
    

    history.scrollRestoration Browser support:

    Chrome: supported (since 46)

    Firefox: supported (since 46)

    Edge: supported (since 79)

    IE: not supported

    Opera: supported (since 33)

    Safari: supported

    For IE if you want to re-scroll to the top AFTER it autoscrolls down then this worked for me:

    var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
    if(isIE11) {
        setTimeout(function(){ window.scrollTo(0, 0); }, 300);  // adjust time according to your page. The better solution would be to possibly tie into some event and trigger once the autoscrolling goes to the top.
    }