Search code examples
jqueryanchorjquery-events

jQuery does not fire when changing the anchor link in the URL... How can I capture this event?


I have a page with accordion-type subsections which are toggled open by clicking on the section title or by clicking a link from a dropdown in the global site navigation.

The intention is to make sections within the page accessible directly from anywhere.

The global menu has links in the format of:

/pagename.aspx#anchor-name
/pagename.aspx#anchor-name2

To capture clicks via the global navigation, I use:

var anchor = window.location.hash;

if (anchor) {
    toggle_element(anchor_name);
}   

within

$(document).ready

Unfortunately .ready fires only the first time the page is loaded.

If I navigate to click on /pagename.aspx#anchor-name, my script runs. If I then click on /pagename.aspx#anchor-name2, nothing happens.

How can I capture this activity?


Solution

  • I ended up using

    window.onhashchange = anchor_change;
    
    function anchor_change() {...}
    

    based on this MozDev's reference and http://caniuse.com/hashchange showing that it is supported in IE8 and above along with most contemporary browsers which covers my use case.

    Note that IE8 could not understand the window.addEventListener("hashchange", anchor_change, false); format, so I had to use the window.onchange = anchor_change; variation.