How to jump to top of browser page

How to jump to top of browser page

I’m writing a modal popup and I need the browser to jump to the top of the screen when the open modal button is pressed. Is there a way to scroll the browser to the top using jQuery?

Solutions/Answers:

Solution 1:

You can set the scrollTop, like this:

$('html,body').scrollTop(0);

Or if you want a little animation instead of a snap to the top:

$('html, body').animate({ scrollTop: 0 }, 'fast');

Solution 2:

Without animation, you can use plain JS:

scroll(0,0)

With animation, check Nick’s answer.

Solution 3:

If you’re using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn’t pop-up out of view, negating the need to scroll. Otherwise,

var scrollTop = function() {
    window.scrollTo(0, 0);
};

should do the trick.

Solution 4:

You could do it without javascript and simply use anchor tags? Then it would be accessible to those js free.

Related:  How to document anonymous functions (closure) with jsdoc-toolkit

although as you are using modals, I assume you don’t care about being js free. 😉

Solution 5:

I know this is old, but for those having problems in Edge:

Plain JS: window.scrollTop=0;

Unfortunately, scroll() and scrollTo() throw errors in Edge.

Solution 6:

you’re using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn’t pop-up out of view, negating the need to scroll. Other