Tag Archives: scrollTo

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:

window.scrollTo(0,0);

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:

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

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

jQuery: Scroll to the Top of a Page CodeUnit 04 NOV 2009

jQuery-logoMy current project requires me to split up a particularly long survey into chunks, allowing a survey taker to only submit those chunks that he/she feels like submitting and ignoring the rest.

Now to be all spiffy I simply fade out the affected chunk once the user clicks submit and then throw back a growl notification at him thanking him for his submission. However, it was at this point that I hit a small snag in that the growl works visually best if you scroll all the way back up to the top of the page and thus I set about looking on the web for a decent scrollTo jQuery plugin as quite simply I don’t have the time to whip up my own.

All of which brought to me the discovery of Ariel Flesler’s nifty jQuery.ScrollTo plugin which you can read more about (and grab) here: http://flesler.blogspot.com/2007/10/jqueryscrollto.html

Add the link to the plugin in your page and hey presto, when you want to scroll the screen all the way up, simply do this:

$.scrollTo(0);

 Nifty.