tags:

views:

297

answers:

1

Say I've loaded some arbitrary HTML page into my browser. Then into the address bar I append "#anchor-name" and hit enter.

Since I only added an anchor and didn't call a different page, the browser does not make another call to the server. So there is no onLoad event, etc.

Nonetheless, could some Javascript on the page detect this action? How? What's the event?

I think the answer is "no." Please prove me wrong.

Thanks

Note: Please assume there is no query string in the URL. It ends with "/index.html" or "/".

Related question: does it matter if an anchor named "anchor-name" actually exists on the page?

+4  A: 

IE8 has an onhashchange event that is what you are looking for.

For the rest of the browsers, however, the "common" technique is to set a piece of code using setInterval that regularly checks the hash to see if it has changed since the last time it was called, and perform an action if it has. This article, however, offers a solution to onhashchange that doesn't rely on setInterval, however it looks to be way too clunky to reliably use. I would just stick to setInterval for all browsers:

var hash = window.location.hash;
setInterval(function() {
    if(hash != window.location.hash) {
        hashChanged();
        hash = window.location.hash;
    }
}, 2000); // 2 second timer, should be fine

It doesn't matter if there's no element with the hash provided.

Paolo Bergantino
setInterval() does seem like the best option. Thanks.The article referenced uses the onScroll event. While pretty clever, it does require an anchor with the right name to actually exist. So it's not feasible if you need to support arbitrary anchor names. Just thought I'd note that for posterity.
mcqwerty