Animated scrolling with jQuery

It’s simple enough to use anchor tags to permit a user to move from one part of a page to another.

Well, perhaps not “move” as much as “jump jarringly”. Isn’t there some way of doing the same thing with a little more panache?

Of course there is. jQuery has two functions, offset and animate, that can be combined to provide a smooth transition from origin to destination.

First, we need an origin. For ease of discussion let’s assume we have a set of navigation links, all of which point to a different destination on our page:

<ul class="origin">
  <li title="services">our services</li>
  <li title="faq">frequently asked questions</li>
  <li title="contact">contact us</li>
</ul>

It doesn’t matter what html element you use for the origin — link, div, image, &c. — as long as you can pinpoint it discretely in the DOM.

Yes, these are list items and not links. No, they don’t need to be. Yes, one should probably add a pointer to them to let people know they’re clickable.

Next, we need a destination that is, in some way, affiliated with the origin, in this case via an id that corresponds to the origin’s title:

<div id="faq">
frequently asked questions
...
</div>

I’m using title for the origin and id for the destination because that’s the way that makes the most sense to me. However, that’s certainly not the definitive method. Do what you want. Life’s a celebration.

Finally we need a little jQuery to tie everything together:

<script src="//code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
  if ($('.origin li').click(function(event) {

    // determine the destination
    var destination = '#'+event.target.title;

    // calculate the offset
    var offset = $(destination).offset().top;

    // animate the scroll
    $('html').animate({scrollTop: offset}, 400);

  })
);
</script>

There are lots of configuration options, all lovingly documented elsewhere.