JS: Add, Remove Event Handler
Method to Add or Remove Event
-
node.addEventListener(eventName, functionName, false)
-
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 the property key
"target"
. That is,eventObject.target
. 〔see What is “this” in a 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
Here is the HTML code:
<div id="xclick406">click me</div> <p id="xoutput105"></p>
Here is the JavaScript code:
const xclick406 = document.getElementById("xclick406"); const xoutput105 = document.getElementById("xoutput105"); const ff = (() => { xoutput105.textContent = xoutput105.textContent + "clicked "}); xclick406.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
Basic DOM Element Methods
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Get Element Parent, Child, Sibling
- DOM: NodeList vs HTMLCollection
- JS: Iterate HTMLCollection
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element Content
- JS: Add, Remove Event Handler