I came across an article on Learning jQuery about animating the scrolling between same-page links (i.e. anchors). Basically one block of code does this automatically, but I came across a problem that it was trying to do the same for anchors on other pages, which obviously wouldn’t work.

The line in question:

~~~ .prettyprint $(‘a[href*=#]’).click(function() {

This line selects all `a` elements with a hash (`#`) in its `href` attribute, but this also selects links to anchors on other pages. I changed it to this:

~~~ .prettyprint
$('a[href^=#]').click(function() {

So instead of matching a hash anywhere in the href attribute, this code only matches the hashes at the beginning. Other than that, the rest of the code is the same as in the article. You can see the effect here by clicking on the link in the footer to go back to the top of the page.


  • Hi there,

    Thanks for linking to my entry! Actually, though, I put that selector — $(‘a[href*=#]’) — in there intentionally, to account for all possible ways that someone could link to an anchor on the same page. The next line in my script limits it to anchors on the same page with this if condition:

    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname)

    Of course, if you know that you’ll always begin your same-page hrefs with the hash, then your method is preferable, and that next condition is unnecessary. But I felt I should make mine as generic as possible to account for an weirdness that might result from a wysywig editor in a CMS or an inexperienced content person.

    The script does have another problem, though, which I’ll be addressing in a follow-up entry soon.

  • Interesting, because with the original code my external anchors wouldn’t work — nothing happened when I clicked them, but once I changed the selector to [href^=#] it worked fine.

    Probably my bad copying ;).