Smooth Scrolling with ScrollBox.js

Somebody wrote an email asking for a good way to do smooth scrolling with my scrollbox library. If you have some code that will do smooth scrolling on a div, you can use it. The scrollbox will watch what’s going on and automatically update the handle as well as its internal state. If you’re looking for a good solution, here’s a simple one that uses scriptaculous.

	Effect.SmoothScroll = Class.create(Effect.Base, {
		initialize: function(scrollbox, options){
			this.scrollbox = scrollbox;
			this.options = Object.extend({
				to: scrollbox.scroll_pos,
				from: scrollbox.scroll_pos,
				duration: 0.5
			}, options || {});
			this.start(this.options);
		},
		update: function(position){
			this.scrollbox.scrollTo(Math.round(position));
		}
	});

If you have already created a scrollbox like this, var sb = new ScrollBox($('somebox'), {auto_hide: true});, you could trigger a smooth scroll like this:

	//scroll to the top over half a second (the default duration)
	new Effect.SmoothScroll(sb, {to: 0}); 

	// or

	// scroll from top to bottom over 5 seconds
	new Effect.SmoothScroll(sb, {from: 0, to: sb.scroll_max, duration: 5});

You can embellish this with any of the other scriptaculous goodness you see fit. I noticed when testing this that it automatically applied a nice ease in/out effect to the timing of the scroll. Pretty sweet.

Leave a Reply