JS DOM: Add / Remove Event Handler

By Xah Lee. Date: . Last updated: .

Add event handler

node.addEventListener(eventName, functionName)

Adds a event handler.

eventName is a string representing a event.

functionName is a function that will be called when the event happens.

The event handler function functionName is passed a eventObject as argument.

The element that fired the event can be accessed by eventObject.target.

Remove event handler

node.removeEventListener(eventName, functionName)
Remove the function that was attached to the event.

Example: click button

Here is a simple click event.

click me

Code

<div id="xclick_tkvgQ">click me</div>

<p id="xoutput_kqy5B"></p>
const xclick_tkvgQ = document.getElementById("xclick_tkvgQ");

const xoutput_kqy5B = document.getElementById("xoutput_kqy5B");

const ff = (() => { xoutput_kqy5B.textContent = xoutput_kqy5B.textContent + "clicked "});

xclick_tkvgQ.addEventListener ("click", ff);

This is a simple example of a Event. The event is "click". When user clicks, the browser fires the event, then calls the function attached to that event. (function for this purpose is called the “event handler”.)