Make Internal Links Scroll Smoothly with JavaScript
Pages: 1, 2, 3, 4, 5, 6
Scrolling a Step
One last thing: how do we actually do the scrolling? The key function here is window.scrollTo(), to which you pass X and Y positions; the browser then scrolls the window to that position. One minor wrinkle is that you can't scroll all the way to the bottom. If the Y position you pass in is less than a window's height from the bottom of the document, the browser will scroll down only as far as it can--obviously, it can't go right down to the link if the distance to the bottom of the page is less than the height of the window.
Now, we need to check for that; the best way to do so is to see whether the positions before and after the scroll are the same:
function scrollWindow(scramount,dest,anchor) {
wascypos = ss.getCurrentYPos();
isAbove = (wascypos < dest);
window.scrollTo(0,wascypos + scramount);
iscypos = ss.getCurrentYPos();
isAboveNow = (iscypos < dest);
if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
// if we've just scrolled past the destination, or
// we haven't moved from the last scroll (i.e., we're at the
// bottom of the page) then scroll exactly to the link
window.scrollTo(0,dest);
// cancel the repeating timer
clearInterval(ss_INTERVAL);
// and jump to the link directly so the URL's right
location.hash = anchor;
}
}
Note that, because we scroll in specific integral increments, this step might have taken us past our destination. Thus, we check whether we were above the link before and after the scroll; if these two locations are different, we've scrolled past the link, and as such, we've finished. If we're finished, we cancel the timer and set the page's URL (by setting a bit of the location object) so that it looks as if the browser had handled the link.
Making the Effect Happen
To apply this effect to a page, simply put the JavaScript code in a file called smoothscroll.js and include that file in your HTML page's HEAD as follows:
<script src="smoothscroll.js" type="text/javascript"></script>
That's all you need to do. This approach follows the principles of unobtrusive DHTML, making it easy for everyone to use. The script starts itself up when the page is loaded, by attaching itself to the page's "load" event:
ss.addEvent(window,"load",ss.fixAllLinks);



