Wednesday, August 16, 2006

Animated Page Scrolling with Javascript

It might seem like nothing but eye candy, but it can be a great way to lead a user around a page while still giving them some context as to where they are. Clicking on an anchor link that jumps straight to another part of the page can be jarring and disorienting. Animating the scroll shows clearly where they came from and how to get back there. It's also a great example of how to create private methods and members in Javascript objects. See the code in action on the example page.

The fundamental idea is simple: using window.scrollTo(x, y), it's possible to jump the scroll bar to any point on the page. If we were to jump a couple of pixels at a time, over 2 or 3 seconds, it would look like the window was being scrolled through. Couple that with some functions that find all links to an anchor on a page (#home, #end, etc.) and attach an onclick event to them, and you have a flashy effect that degrades gracefully on browsers that don't have Javascript enabled. Non-JS users still get the normal anchor links, and everyone else gets the scrolling animation. Read more

Tags: , , ,


Post a Comment

<< Home