Soft-scroll to an anchor with jQuery

Updated . Posted . Visible to the public.

This snippet makes links that refer to an anchor (like "<a href="#something">...</a>") scroll softly to it.\
In this example we only do it for links that also own a data-animate attribute.

$('a[href^="#"][data-animate]').live('click', function() {
  var hash = $(this).attr('href');
  var offset = $(hash).offset();
  if (offset) {
    $('html, body').animate({ scrollTop: offset.top }, 'slow');
    location.hash = hash;
    return false;
  }
});

Note that this could basically work for any element whose offset() you can read. Here, we just fetch the target by the element's href attribute.

If you can get away with it (i.e. the hash change on the URL is not important) you can remove location.hash = hash; for a smoother behavior (browsers will jump on anchor changes).

Arne Hartherz
Last edit
Judith Roth
Keywords
animated, scroll, smooth, scroll
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2011-06-06 13:01)