Animated Scrolling in jQuery

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:

[sourcecode language=’jscript’]$(‘a[href*=#]’).click(function() {[/sourcecode]

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:

[sourcecode language=’jscript’]$(‘a[href^=#]’).click(function() {[/sourcecode]

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.

This entry was posted in Software, Web Development and tagged , , , , , . Bookmark the permalink.

5 Responses to Animated Scrolling in jQuery

  1. Matt says:

    That’s pretty sweet. The thing jQuery makes so easy, but would we so complicated without it… is amazing!

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

  3. Robin says:

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

  4. Robin says:

    Oh, and sorry about your comment getting marked as spam, Akismet seems to be a bit off lately.

  5. Heh, no problem, Robin. I was wondering why the comment didn’t show up, though. Cheers.