robinadr

Tagged animation

A while back I posted about automatically scrolling between internal links with some jQuery magic (which in turn was based on a tutorial by Learning jQuery) but one problem with it was that there was no way for the user to link to the anchor.

The problem was that because the function has to return false in order to keep the browser from jumping straight through to the anchor and skipping the animation. So I added another line to the code, taking after AJAX pseudo-permalinks, that adds the hash link (e.g. #anchor) back onto the URL in the address bar after a timeout matching the animation.

Here’s the line in question:

[sourcecode language="javascript"]setTimeout('window.location = window.location + "' + this.hash + '";', 1000);[/sourcecode]

Here’s the full code:

[sourcecode language="javascript"]$(function() {
    $('a[href^=#]').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length && target || $('[name=' + this.hash.slice(1) + ']');

            if (target.length) {
                var targetOffset = target.offset().top;
                $('html,body').animate({ scrollTop: targetOffset }, 1000);
                setTimeout('window.location = window.location + "' + this.hash + '";', 1000);
                return false;
            }
        }
    });
});[/sourcecode]

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.