robinadr

Tagged anchors

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.