Choose an Event Listener Mechanism

Alex Reardon
InstructorAlex Reardon

Share this video with your friends

Send Tweet
Published a year ago
Updated a year ago

Sometimes you need to use addEventListener to listener to particular events as there are no corresponding HTML attribute or object property event handlers for the event.

Instructor: [0:00] It is possible to listen for events using HTML attribute event handlers, element property event handlers, and addEventListener. I almost always use addEventListener to listen to events, as it allows multiple event listeners to be added to a single event target, as well as providing a lot more control over the binding.

[0:21] You're often free to choose what mechanism you like to listen to events. However, some events do not have corresponding HTML attributes or element properties. You will need to use addEventListener in that case. For example, DOMContentLoaded has no corresponding HTML attribute or element property event handler, so you'll need to use addEventListener to listen for that event.

[0:48] A good place to see what event listener mechanisms you have available to you is the MDN event reference. Firstly, I'm going to look up the click event. I can come in here, and I can see it. Click has a corresponding event handler property. I can go into here and find out a bit more about that.

[1:06] If I go back to the root page, I'm now going to look up the DOMContentLoaded event. If I come in here, I can say, "Oh OK, DOMContentLoaded doesn't have an event handler property, so I'm going to need to use addEventListener."