Categories:

Scrolling a window

Same concept, just different actions. The scrollBy() and scrollTo() methods allow you to programmatically scroll the window either up-down, left-right, or both. Here they are, neatly listed in a table:

Methods Description
scrollBy(dx, dy) Scrolls a window by the specified amount in pixels
scrollTo(x, y) Scrolls a window to the specified pixel values

I think it's pretty self explanatory how each of them work, so I'll simply concentrate on a couple of their applications instead.

Example #1: Preventing the user from scrolling down

In this first example, the scrollTo() method is used to "lock up" the scrolling of the page. This is useful, say, when you wish the user to only be able to interact with the page when it has completely loaded. The implementation is quite simple, really. Just continuously call window.scrollTo(0,0), and only disable it after the page has finished loading. Here's the full working code:

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

For all those unfamiliar with the setInterval method used above, it's a JavaScript method that operates similar to setTimeout, except setInterval continuously runs a function at the intervals specified by it's second parameter (as opposed to just once).

Example #2: Link as scrollbar

Now, with the existence of the moveBy() method, you can easily simulate the default browser scrollbars using script. This is very useful, for example, in a frames page situation, where one of the frames need to be scrollable, but you do not wish the default scrollbars to appear (for aesthetic reasons). Simply use the newly found method! Now, I'm not going to recreate an entire frames page just for sake of demonstration (as special as you all are to me, the night is not young at this moment). However, below shows how the core code may look like, using text links as replacement for the default scrollbar:

<a href="javascript:parent.frame2.scrollBy(0,-5)">Scroll Up</a>
<a href="javascript:parent.frame2.scrollBy(0,5)">Scroll Down</a>

Where frame2 is the name of the frame to scroll.

Let's wrap this tutorial up by seeing how to use the new "resize" methods...