Rynee Rynee - 1 month ago 5
Javascript Question

Get URL hash during click event/function

During a jQuery click event function, I understand the click event is fired before the underlying event is completed (and URL is updated)... so you can control the event. Which means the hash of the link isn't yet available via

window.location.hash


Is
e.target.hash
better than reaching into the
<a>
element itself to get the hash value; or passing the necessary variable via an
onclick
event? "Better" defined as cross-browser compatibility or more prone to errors.

For example:

<a class="accountLink" href="#account/123456">Account 123456</a>


$('.accountLink').click(function(e){
console.log(e.target.hash);
console.log(window.location.hash);
});


Log:

#account/123456
(blank on initial click)


https://jsfiddle.net/r1xpsut1/1/

Answer

Given your requirements it sounds like the onhashchange event of the window would be more appropriate:

window.onhashchange = function() {
    alert(window.location.hash);
}

Updated fiddle