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

Shay Paustovsky
Shay Paustovsky
969 Points

Event object and addEventListener() method

Hello,

So I am totally confused by this topic and would love if someone could explain it because I'm lost.

document.addEventListener('click', (event) => {
      console.log(event.target)
}
   );
  1. Why do we use the 'event' parameter?
  2. Where does it come from ?
  3. How does it all works together.

Those are rookie questions but I'm genuinly confused by this topic and would love if someone could clarify it to me.

1 Answer

Antonio De Rose
Antonio De Rose
20,885 Points

button.addEventListener('click', event => { console.log(event.target)l });

first and foremost, these are what you call, callback functions, callback functions are, functions passed into another functions parameter to take an action. Every html element is an object, above example, button is an object, and have got it's function named addEventListener, and this function would take 2 parameters, first being type of action, which is click and the second parameter, is the function you want to execute, when the action happens.

1) why do we use the event parameter ? as said above, the second parameter, has an ability to take, click event (famous "this") as a parameter, it is not necessary to use, you can leave it even blank, but the only use, would be if you want to know, from why / when / what object, is calling the function.

2) Where does it come from ? like mentioned, it is by default, a browser implementation, in this case, addEventListener, by default allows you to access, the object, which is calling itself by the way, it need not have to be called event. You could name it as anything you wish.

3)How does it all works together? I hope you got this from the above all explanation.

Shay Paustovsky
Shay Paustovsky
969 Points

Thank you so much Antonio,

if you don't mind one more question ?

How does the callback function has the ability to take a click event and what does it have to do with "this".

Thank you