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.
Duration
1 min
Access
Pro
Transcript
Available
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.
Video Transcript
Instructor: 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.
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.
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.
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."
Duration
1 min
Access
Pro
Transcript
Available
Course lesson
Choose an Event Listener Mechanism
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.
Access required
This lesson is available with an active egghead membership.