2

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/

0

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks Rory! One function watching for the hash update will definitely fit in this instance and help simplify.
0

According to Mozilla Web API, Event.target is supported in every modern browser, except for Internet Explorer 6 to 8 where Event.srcElement is used instead, so if you want to support it, you can use:

var target = (event.target || event.srcElement);

In fact, said .event property is defined as:

The DOM element on the lefthand side of the call that triggered this event, eg:

element.dispatchEvent(event)

It is therefore the same as reaching the <a> youself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.