Read more

Soft-scroll to an anchor with jQuery

Arne Hartherz
June 06, 2011Software engineer at makandra GmbH

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;
  }
});
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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).

Posted by Arne Hartherz to makandra dev (2011-06-06 15:01)