views:

28

answers:

1

Hi there - 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.

A: 

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);
});
Andrew Bullock
Thank you for the answer, but it doesn't work properly. It works fine for pages where the link and the anchor are on the same page, but it prevents all links from working at all.Another point to note is that most of the time, the link to the anchor will be coming from another page, so it'll need to be able to grab the # from the url.Thank you.
Daniel
well for the first part, add a class to the link that denotes it as being "same page" then use `$('a.myclass')` as your selector.For the second part, i wouldnt do that. sounds like bad usability
Andrew Bullock
Use `$('a[href^="#"]')` to only select links that go to anchors on the page.
Liam
much better idea @Liam
Andrew Bullock