JavaScript: Add/Remove Event Handler

By Xah Lee. Date: . Last updated: .

This page shows you how to add/remove event handler.

node.addEventListener(event_name, function_name, false)

Adds a event handler.

event_name is a string representing a event.

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

The event handler function function_name is passed a event_object as argument.

The element that fired the event can be accessed by the property key "target". That is, event_object.target. [see What is “this” in a event handler?]

node.removeEventListener(event_name, function_name)
Remove the function that was attached to the event.

Example

Here is a simple click event.

click me

Here is the HTML code:

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

<p id="output28161"></p>

Here is the JavaScript code:

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

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

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

click40667.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”.)

List of Event Names

https://developer.mozilla.org/en-US/docs/Web/Events

https://www.w3.org/TR/DOM-Level-3-Events/

BUY
ΣJS
JavaScript in Depth

DOM Scripting

Overview

DOM Methods

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc