Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
Yarin Avatar asked Nov 18 '10 01:11

Yarin


1 Answers

Cross-browser, pure JavaScript solution:

document.body.scrollTop = document.documentElement.scrollTop = 0; 
like image 193
Niet the Dark Absol Avatar answered Sep 23 '22 02:09

Niet the Dark Absol