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).
Posted by Arne Hartherz to makandra dev (2011-06-06 13:01)