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!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn More)

  • Related Content by Tag