DOM: Add/Remove Event Handler

By Xah Lee. Date: . Last updated: .

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

Here's a simple click event.

click me

Here's the HTML code:

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

<p id="outputBox"></p>

Here's the JavaScript code:

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

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

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

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

addEventListener

node.addEventListener(event_name, function_name)

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's “this” in a event handler?]

removeEventListener

node.removeEventListener(event_name, function_name)

List of Event Names

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

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

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js