0

I got this code when learning JavaScript:

myLink.onmouseover = showLinkAttr;
function showLinkContent(evt) {
    if (evt) {
        var url = evt.target;
    }
    else {
        evt = window.event;
        var url = evt.srcElement;
    }
..............

I don't know why we need to check event handler parameter evt before creating it. My thinking here is this code is redundant because evt doesn't exist (this code is in the beginning of the script file), show we should create it without checking it, like this:

  myLink.onmouseover = showLinkAttr;
  function showLinkContent(evt) {
        evt = window.event;
        var url = evt.srcElement;

However, as I am new to JavaScript, and the code below was written by an expert. So, could you tell me why she using it instead of the one I wrote below?

1
  • To accept an answer on some of your other questions, you need to click the outline of the tick below the answer's rating. Commented Sep 10, 2012 at 8:39

2 Answers 2

2

You're half way there... evt will only be undefined when the client is running that miserable excuse of a browser that is known as IE.

IE doesn't pass the event object to the handler, but has only 1 global event object. That's why your event handler checks to see if the event object has been passed as an argument, if not, it gets the global event object. This can be written a lot shorter though:

evt = evt || window.event;//evt is equal to itself, if it's not undefined, else it's a reference to the global object

Ditto for the target (you called it var url, which is confusing and perhaps wrong):

var target = evt.target || evt.srcElement;

The target (or srcElement) returns a reference to a DOM element (the one on which the event was fired), not a url, like your varname would have you believe.
The double pipe || is known as the default operator.

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

Comments

0

The code is catering to the inconsistencies between different browsers. Look at this article for details: http://www.quirksmode.org/js/introevents.html

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.