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? ;)