How to Scroll to the Top of a Page with Plain Old Javascript CodeUnit 19 MAY 2010

Sometimes a person forgets the simple things in life, so every now and then it is a good thing to be reminded of them. Like scrolling to the top of a window for example.

Plain old vanilla Javascript comes equipped with two really handy functions, namely scrollBy(dx,dy) which allows you to scroll a window by the specified number of pixels and scrollTo(x,y) which forces a window to scroll to the specified co-ordinates, with the specified point referring to the top left corner of the window.

Now with this said, it becomes painfully obvious how you would scroll to the top of a window using Javascript alone. Simply call:


As you can figure out, this simply tells the window to draw itself with the top left corner sitting at points 0,0, in other words, at the top of the screen.

Of course, this could be extended to say for example, “locking” the screen while a page loads – in other words deny the scrolling ability to a user while a page’s contents is still in the process of loading.

To do this we will make use of the handy setInterval function:

<script type=”text/javascript”>
var lockit=setInterval(“window.scrollTo(0,0)”,10)
<body onLoad=”clearInterval(lockit)”>

Simple, but useful to be reminded of it, no? ;)

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Ya I agree I really have forgotten this thanks for the review.

  • Eek, yet another potentially hand-craafted spam comment that got through! O.o