Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) 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 (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 :)


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
210,070 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
210,070 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.