Search code examples
javascriptjquerybrowser-historydeep-linkinghashbang

Internal Links with jQuery Address


I'm trying to implement the lovely Address plugin to handle internal links for prettier links and use of the back button. I managed to get it to work, however the one thing I noticed, is that when it changes the URL from /#section to /#/section if the user then copies that URL and tries to open it in a new window (or send to a friend) it does not take the user to that section on the page. Obviously because it's not recognized as an anchor anymore.

How can I get it to be on the right section when a user navigates via the URL?

Below is the snippet of code I'm using in accordance with jQuery Address:

$('nav a').click(function() { 
    var pageTitle = 'Kevin Dare Foundation | ' + $(this).html(); 
    $.address.value($(this).attr('href').replace(/^#/, ''));
    $.address.title(pageTitle);
});

Also here is the link to see it in action: http://nickdimatteo.com/kjd


Solution

  • The simplest way may be to trigger the code you have when the document loads if there is a document.location.hash:

    $('nav a').click(function() { 
        var pageTitle = 'Kevin Dare Foundation | ' + $(this).html(); 
        $.address.value($(this).attr('href').replace(/^#/, ''));
        $.address.title(pageTitle);
    });
    
    $(document).ready(function() {
        var hash = document.location.hash.replace(/^#\//, '');
        if(hash) {
            $('nav a[href="#' + hash + '"]').trigger('click');
        }
    });