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

Shay Paustovsky
Shay Paustovsky
958 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,859 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
958 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