in Web & Tech

jQuery scrollTo without a Plugin

Today, when I quickly needed a solution to smoothly scroll to another position on the same page I was hesitant to just throw another jQuery plugin into my site so I started looking for a more lightweight solution. Here’s what I found:

$('html, body').animate({
    scrollTop: $("#elementID").offset().top
}, 2000);

It can just be put inside any callback function, e.g. click(). The following example will scroll to an ID called page-title upon clicking a link with the class scroll-to-title (in 500 ms):

$("a.scroll-to-title").click(function() {
  $('html, body').animate({
    scrollTop: $("#page-title").offset().top
  }, 500);
});

Thanks to A Beautiful Site for sharing!

Write a Comment

Comment

  • Related Content by Tag