DOM2 Events defines two methods for assigning and removing event handlers: addEventListener() and removeEventListener(). These two methods are exposed on all DOM nodes. They take three parameters: the event name, the event handler, and a Boolean value, true for calling the event handler during the capture phase and false (the default) for calling the event handler during the bubble phase. For example, adding a click event handler to a button might look like this:

let btn = document.getElementById("myBtn");
btn.addEventListener("click".() = >{
	console.log(this.id);
},false);
Copy the code

The above code adds an onclick event handler to the button that fires during the event bubble phase (because the last parameter value is false). Like DOM0 (btn.onclick=function(){console.log(“Clicked”)}), this time handler also runs in the scope of the element being attached. The main advantage of using the DOM2 approach is that you can add multiple time handlers for the same event. Consider the following example:

let btn = document.getElementById("myBtn");
btn.addEventListener("click".() = >{
	console.log(this.id);
},false);
btn.addEventListener("click".() = >{
	console.log("Hello world!");
},false);
Copy the code

Here we add two event handlers to the button. Multiple event handlers are fired in additive order, so the previous code prints the element ID and then displays the message “Hello World!” .

Event handlers added via addEventListener() can only be removed using removeEventListener() and passing in the same parameters as when they were added. This means that anonymous functions added using addEventListener() cannot be removed, as shown in the following example:

let btn = document.getElementById("myBtn");
btn.addEventListener("click".() = >{
	console.log(this.id);
},false);

// Other code

btn.removeEventListener("click".() = >{    // No effect
	console.log(this.id);
},false);
Copy the code

This example adds an anonymous function as an event handler via addEventListenter(). RemoveEventListener () is then called again with what appear to be the same parameters. But the second argument is completely different in time from the one passed to addEventListener(). The event handler passed to removeEventListener() must be the same as that passed to addEventListener(), as shown in the following example:

let btn = document.getElementById("myBtn");
let handler = function(){
	console.log(this.id);
};

btn.addEventListener("click",handler,false);

// Other code

btn.removeEventListener("click",handler,false); / / have the effect
Copy the code