Smoothly scroll to an element without a jQuery plugin

A drawing of a cartoon man pointing upwards

Heads up! This post was written in 2010, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.

— Cory

You know that special effect where you click on a link and your browser smoothly scrolls down to the appropriate section of the page? Pretty slick, right? Here are a couple snippets so you can do the same thing on your own website.

Scroll to a specific element #

Here's how to programmatically scroll to any element on the page. If you're using jQuery, you don't need a plugin. It's very simple:

$('html, body').animate({
  scrollTop: $("#target-element").offset().top
}, 1000);

This will scroll the page down to #target-element over a period of one second (1,000 milliseconds = 1 second).

Scroll to the selected anchor #

You can take things a bit further and animate scrolling for all anchors on your page. The following snippet will watch for clicks on any link that points to an anchor and smoothly scroll down to it:

$('a[href^="#"]').on('click', function(event) {

  var target = $(this.getAttribute('href'));

  if (target.length) {
    $('html, body').stop().animate({
      scrollTop: target.offset().top
    }, 1000);

See it in action #

See the Pen cybdG by Cory LaViska (@claviska) on CodePen.