Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Responding to User Interaction The Event Object

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 (event.target.tagName == 'LI') { event.target.textContent = event.target.textContent.toUpperCase(); } });

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

so, is the other solution better?why?

Thanks :)

Hi,

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?

Thanks

2 Answers

Steven Parker
Steven Parker
231,236 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
231,236 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.