This course is out of date and does not reflect Frontend Masters current standards. We now recommend you take the JavaScript: The Hard Parts course.

Check out a free preview of the full Advanced JS Fundamentals to jQuery & Pure DOM Scripting course:
The "Event API" Lesson is part of the full, Advanced JS Fundamentals to jQuery & Pure DOM Scripting course featured in this preview video. Here's what you'd learn in this lesson:

The addEventListener method is used to register an event to any DOM element. Conversely, removeEventListener will remove that event handler. Using the console Justin demonstrates how to use these methods.

Get Unlimited Access Now

Transcript from the "Event API" Lesson

>> [MUSIC]

>> Justin Meyer: To listen to an event in the DOM you do element.addEventListener. You give it the type of event you want to listen to. You give it a function to call back and then there's this capture flag which we'll talk about what that does. And then to remove an event, you call element.removeEventListener and you,

>> Justin Meyer: And you give the same event name and the same handler and the same capture flag. We'll talk about that means. So that looks like this. If I want to listen to when someone clicks breeds on the page, on the element I say addEventListener, give it a click, give it a function, and we'll talk about what this means in a second.

[00:00:50] Pretty, pretty straightforward, hopefully. Are there people who've never seen this? Everybody kinda seen addEventListner? Most people? Good, Cool. To removeEventListener, you always have to pass the same function that was used to bind in addEventListener, right. So if I did addEventListener like this. So I want to listen on breeds when it's clicked and we'll console.log('clicked!').

[00:01:18] I cannot do this. I can't just pass a function that looks the same as the function passed to the addEventListener. Because these are two different functions in memory. You have to pass the same function back. So the way to do this is to typically make sure you save a reference to your function in a variable.

[00:01:45] Then pass that variable and therefore that function to addEventListener, so that later, you can remove the event listener. So let's see this in action.
>> Justin Meyer: So I'm going to get my breeds, I'm going to add an event listener to it.
>> Justin Meyer: But wait, first I'm going to save my listener, I'm gonna do a handler.

[00:02:21] I'm gonna create a function. And I'm going to console.log("clicked!"). Then I'm going to add an event listener to say when someone clicks it, call back this function. Actually not this function, sorry, handler. Now when I click this ul, I get clicked, awesome. And to stop listening, I'll do removeEventListener.

>> Justin Meyer: Now when I click, nothing happens. So I think we're about to see all the different types of events you can listen to.
>> Justin Meyer: No, we're gonna do add a bind method.