Tagged links

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;