Reputation: 441
due to the nature of my site, I often have to link to anchors listed within a page, rather than just to the page itself. An example can be found here: http://www.unknowntales.net/chapter/route/choice/#chapter3
What I'm looking for is some jQuery code which I can use to make the page slowly scroll down to the anchor, rather than jumping to it directly.
Can anyone help me out? Thank you.
Upvotes: 2
Views: 805
Reputation: 37398
assuming your html is:
<a href="#someid">click me</a>
<h1 id="someid">some heading<h1>
this should work
$('a').click(function(e) {
e.preventDefault();
var targetOffset = $($(this).attr('href')).offset().top;
$('html,body').animate({ scrollTop: targetOffset - 100 }, 500);
});
Edit: What Liam said (see comment below)
Upvotes: 3
Reputation: 3091
This is something i put together a while back.
$('a', this)
.each(function(e) {
var url = $(this).attr('href').replace(/^\s/, '').replace(/\s$/, '');
var parts = url.split("#", 2);
var anchors = $("#" + parts[1] + ", a[name='" + parts[1] + "']");
if (anchors.length > 0) {
$(this).click(function(evt) {
evt.preventDefault();
$('html, body')
.animate({
scrollTop: $(anchors.get(0)).offset().top
}, {
duration: 1500,
specialEasing: {
scrollTop: 'easeOutQuint'
}
});
});
}
});
If i edited this again I would replace my anchor filtering with $('a[href^="#"]') liam's selector.
Upvotes: 0