Writing a quick jQuery plugin
19 July 2008
I needed a short snippet of Javascript code to scroll the browser window for a usability enhancement I aside from the variations in IE/Firefox scrollTop property, the code is pretty straightforward:
function scrollTo(element) {
g = jQuery(element).offset().top;
smoothScroll = setInterval(function() {
var distance = (document.body.scrollTop || document.documentElement.scrollTop) - g;
if (Math.ceil(distance) > 5) {
window.scrollBy(0, 0 - distance / 5); // scroll the window
} else {
clearInterval(smoothScroll); // we have arrived, so cancel the interval
}
}, t);
}
scrollTo(jQuery('#error_message')); // now call the script
The distance remaining is divided each time to slow down the scrolling speed as we approach the target. This gives a nice smooth effect.
This project used jQuery heavily, so wouldn’t it be nice just to add scrollTo() on the existing code? All I need to do is attach the function to jQuery as a plugin.
jQuery.fn.scrollTo = function(duration) {
return this.each(function() {
var t = duration || 20,
g = jQuery(this).offset().top; // only scrolls to first matched element
smoothScroll = setInterval(function() {
var distance = (document.body.scrollTop || document.documentElement.scrollTop) - g;
if (Math.ceil(distance) > 5) {
window.scrollBy(0, 0 - distance / 5);
} else {
clearInterval(smoothScroll);
}
}, t);
});
};
Now I can do:
jQuery('#error_message').scrollTo();
or even:
jQuery('#error_message')fadeIn().scrollTo();
It could do with a little cleaning up - weird effects will happen if you pass in more than one object to scroll to, but it’s a good start. This script can now be easily dropped into other projects using the jQuery library.