JavaScript JavaScript and the DOM Responding to User Interaction The Event Object

more fire
more fire
Courses Plus Student 7,253 Points

Why do we need the event object as parameter for the callback function?

I came up with this (just the first/mouseover-part as example):

listDiv.addEventListener('mouseover', () => { if ( == 'LI') { =; } });

..without the event object as parameter and it works perfectly fine.

so, is the other solution better?why?

Thanks :)


I had the same question and don't really understand the explanation provided by Steven. Anyone else have an idea why the event is used here and why it has no effect on the code?


2 Answers

Steven Parker
Steven Parker
207,988 Points

Without having defined it yourself, the "event" being referenced is the property of the Window object.
Quoting from the MDN documentation:

The read-only Window property event returns the Event which is currently being handled by the site's code. Outside the context of an event handler, the value is always undefined.

You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.

Steven Parker
Steven Parker
207,988 Points

Restating the points from the documentation: there is an "event" global in most browsers where the system puts the same thing you would get in the parameter. So this code works without the parameter by referencing that global variable.

But the global variable isn't supported in every browser, and my go away in future versions of ones where it is, so you should always use the parameter.

Ahhh, get it now. It's just for full browser support. Thanks for the re-wording, it actually really helped clear it up for me.