Joro Seksa
Joro Seksa

Reputation: 1583

Why does this event handler use "e = e || event"?

Can someone explain me what does this line of code means:

function(e) { e = e || event; e.returnValue = false; return false; }

Why is the parameter named e?
If I change it to 'myparam' will it work?
What does e = e mean?

Where is the variable event ( after || ) declared ? What is e.returnValue?

Upvotes: 18

Views: 9487

Answers (3)

powtac
powtac

Reputation: 41050

This piece of code test if an e object exists, else use the object event and assign it to e. After that it sets the attribute returnValue to false and returns false.

This is code which runs on IE and other browsers the same way, no matter if the event object is called e or event.

Upvotes: 1

Steve
Steve

Reputation: 8640

This line is just to make IE8 and below function the same way as all other browsers. All other browsers pass the target element (e) to the event function.

So what this piece of code does is:

If e exists, keep e. If it doesn't exist, you are using an older version of IE and we assign the windows.event object to e. Now all browsers behave the same way.

Upvotes: 5

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

This is all basic event management, although it is missing e.preventDefault()...

To break it down, when an event handler is fired:

  • Some browsers pass a parameter to the callback holding event data (this is the standards-compliant way of doing it)
  • Other browsers (mostly old IE) instead put the event data in window.event (which is accessed here with just event, which is risky since that relies on there being no local variable with that name)

Next, e = e || event; is a standard way of saying "if the parameter was not passed, default it to whatever's after the ||". In this case, if the event parameter is not passed, then it looks for the global variable.

e.returnValue is one of three ways to stop an event from causing its default action. The other two are e.preventDefault && e.preventDefault() (which is conspicuously absent from the code you posted), and return false;

Upvotes: 25

Related Questions