DOM Event Listener

Method addEventListener()

Example :- 
//Below is the syntax to add an event listener that executes when a user clicks a button:
document.getElementById("myButton").addEventListener("click", displayDateTime);
  • The addEventListener() method attaches an event handler to the specified or given element.
  • The addEventListener() method attaches an event handler to an element without overwriting previous or existing event handlers.
  • User can add multiple event handlers to one element.
  • User can add multiple event handlers of the same type to one element, i.e two “click” events.
  • User can add event listeners to any DOM object not only HTML elements. i.e the window object.
  • The addEventListener() method makes it simpler to control how the event reacts to bubbling.
  • User can easily remove an event by using the removeEventListener() method.
Syntax :-
element.addEventListener(event, function, useCapture);

The first parameter (“event”) is the type of the event (like “click” or “mousedown or keydown” or many others.)

The second parameter is the user defined function that we want to call when the event happens.

The third parameter is optional. It is a boolean value specifying whether to use event bubbling or event capturing.

     Note:- User don’t use the “on” prefix for the event; use “click” instead of “onclick”.


How to add an Event Handler to an Element

Example:-
//Alert "My World!" when the user clicks on an element:
element.addEventListener("click", function(){ alert("My World!"); });

You can also do the same by an external “named” function:

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>Event handle on an element</h2>

<button id="myButton">Try it</button>

<script>
document.getElementById("myButton").addEventListener("click", myFunc);

function myFunc() {
  alert ("My World!");
}
</script>

</body>
</html>

Output (Before Click):-

Output (After Click):-


Add Many Event Handlers to the Same Element

The addEventListener() method allows user to add multiple events to the same element, without overwriting existing or previous events:

Example:-
element.addEventListener("click", myFirstFunction);
element.addEventListener("click", mySecondFunction);

You can add different types events to the same element:

Example:-
element.addEventListener("mouseover", myFirstFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("keydown", myThirdFunction);

Add an Event Handler to the window Object

The addEventListener() method allows an user to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support or allows events, like the xmlHttpRequest object.

Input:-
	<!DOCTYPE html>
<html>
<body>

<h2>Event handle on an element</h2>

<p>This example if for the addEventListener() method on the window object.</p>

<p>Try resizing the browser window to trigger or excute the "resize" event handler.</p>

<p id="result"></p>

<script>
window.addEventListener("resize", function(){
  document.getElementById("result").innerHTML = Math.random();
});
</script>

</body>
</html> 

Output (Before Resize):-

Output (After Resize the window):-


Passing Parameters

When user passes the parameter values, the “anonymous function” that calls the specified function will have the parameters:

Example:-
element.addEventListener("click", function(){ myFunc(param1, param2); });

Event Bubbling or Event Capturing

There are two ways of event propagation in the HTML DOM, bubbling and capturing.

Event propagation is to defining the element order when an event happens. If you have a <span> element inside a <div> element, and the user clicks on the <span> element, which element’s “click” event should be handled first?

In bubbling case, the inner most element’s event is handled first and then the outer: So the <span> element’s click event is handled first, then the <div> element’s click event will happen.

In capturing the outer most element’s event will be handled first and then the inner: the <div> element’s click event will be handled first, then the <span> element’s click event.

User can specify the propagation type by using the “useCapture” parameter in the addEventListener() method

Example:-
addEventListener(event, function, useCapture);

The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.

Example:-
document.getElementById("mySpan").addEventListener("click", myFunc, true);
document.getElementById("myDiv").addEventListener("click", myFunc, true);
60.7.	removeEventListener() method
The removeEventListener() method  allow user to removes event handlers that is related with the addEventListener() method:
Input:-
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {
  background-color: grey;
  border: 1px solid;
  padding: 30px;
  color: white;
  font-size: 15px;
}
</style>
</head>
<body>

<h2>Remove event from Dom element</h2>

<div id="myDiv">
  <p>Here div element has an onmousemove event handler that displays a random number every time when user move your mouse inside this grey field.</p>
  <p>Click the button to remove the div's event handler.</p>
  <button onclick="removeHandler()" id="myButton">Remove</button>
</div>

<p id="result"></p>

<script>
document.getElementById("myDiv").addEventListener("mousemove", myFunc);

function myFunc() {
  document.getElementById("result").innerHTML = Math.random();
}

function removeHandler() {
  document.getElementById("myDiv").removeEventListener("mousemove", myFunc);
}
</script>

</body>
</html>

Output (with event handler on mouse move random value will change everytime):-

Output (After remove event the value will not change on mouse move):-