Friday, March 19, 2010

jQuery scroll to element

Here's a simple way to auto scroll to an element of the page really nice.

First you have to add this piece of code (of couse jQuery library must be included in your source code):

jQuery.fn.extend({
scrollTo : function(speed, easing) {
return this.each(function() {
var targetOffset = $(this).offset().top;
$('html,body').animate({scrollTop: targetOffset}, speed, easing);
});
}
});

And then you just scroll to an element id:

$('#element_id').scrollTo(1000);

You can speed up the scrolling by reducing the scroll time. Eg. scrollTo(100)

No comments: