Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to top of page

Tags:

jquery

Is there a simple way to force the browser to scroll to the top if a button is clicked?

I have tried

jQuery('html').scrollTop();
jQuery('body').scrollTop();
jQuery(window).scrollTop();

None of them seem to scroll to the top of the page.

like image 965
James Wilson Avatar asked May 24 '12 21:05

James Wilson


People also ask

How do I scrollTo the top of the page quickly?

Scroll one page at a time in all major browsers including Microsoft Internet Explorer and Mozilla Firefox by pressing the Spacebar key. Move back up the page by pressing Shift + Spacebar or the Home key on the keyboard.

How do I scrollTo the top of the page in HTML?

window. scrollTo(0, 0); …is a sure bet to scroll the window (or any other element) back to the top.

How do I scrollTo the top of a page in Chrome?

The Google Chrome extension Scroll to top button adds a button for users who prefer to use their mouse while navigating in the browser. A button is placed in the upper right corner of the web browser when the user scrolls down on a page. Clicking on that button in the browser scrolls the page back to the top.

How do I scrollTo the top when I click the button?

window. scroll(0, 0) will work just fine in all browsers.


3 Answers

Due to cross browser oddness, some browsers will respond to 'html' and some to 'body'. And maybe its just my luck, but .scrollTop(0) has never worked for me to move the page. Give this a shot:

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

This version is tested and cross browser for all desktop browsers, and mobile devices.

like image 137
Fresheyeball Avatar answered Nov 11 '22 09:11

Fresheyeball


Simple pure javascript, also works in mobile

window.scrollTo(0,0);
like image 39
Mario Avatar answered Nov 11 '22 08:11

Mario


You can use either this:

jQuery('body').scrollTop(0);

or this:

jQuery(window).scrollTop(0);

or finally this:

jQuery('html').scrollTop(0);

So, in order to call the scrollTop method and make your page scrolling you should pass an argument with the numeric value representing the scrollTop position. Otherwise it will work as if you need to get the scrollTop position.

Two last methods should work constantly in all browsers, while the first might not work in some versions of IE.

like image 28
VisioN Avatar answered Nov 11 '22 08:11

VisioN