Introduction to addEventListener JavaScript
The EventTarget interface provides multiple methods for handling the events in javascript on DOM objects. One of the most important methods of EventTarget interface is addEventListener() helps create and define the snippet execution on the occurrence of the event. These events can also be defined on the event supporting objects like AudioNode, AudioContext, XMLHttpRequest.
It is very easy to add an event to any object in javascript by using addEventListener(). We can even add multiple event listeners to a single object that too of the same type. These events will not override each other and will execute properly as expected without affecting each other’s working.
Syntax:
element.addEventListener(event, functionName, useCapture);
The above syntax is explained in detail below by describing each of its content variables:
- Element: It can be any element in current DOM or object that supports event handling like window or XMLHttpRequest.
- Event: It is a case-sensitive string that specifies the occurrence of which the specified action is to be performed. Examples of such events are click, dbclick, mouseover, mousemove, etc. Caution should be taken while specifying the event as this string is case-sensitive and needs a correct word to execute these events properly.
- functionName: This function defines the actual code you want to execute when the above-mentioned event will occur. This function can be either named or anonymous. We will see the example of both of these methods of declaring functions in further part.
- useCapture: This is a Boolean parameter which is by default set to false. This specifies whether the nature of event execution while parent-child structure will be event capturing or bubbling. If we want to capture event execution type, we can send this parameter as true while in all other cases it will show bubbling type of nature while event execution. We will see this working and difference between both of them clearly with the help of examples further.
Examples of addEventListener JavaScript
Given below are the examples of addEventListener JavaScript:
Code:
<!DOCTYPE html>
<html>
<body>
<p>This example will demonstrate the working of addEventListener by calling a method to alert a message when the button is clicked</p>
<button id="demoButton">Greetings for today</button>
<script>
document.getElementById("demoButton").addEventListener("click", function(){ alert("Good Morning! Have a great day ahead.");
});
</script>
</body>
</html>
Output:
1. Named And Anonymous Function Calls
We can mention directly an anonymous function that specifies what has to be done when an event occurs or write a separate named function which specifies the same.
Code:
<!DOCTYPE html>
<html>
<body>
<p>These methods demonstrate that anonymous as well as named functions can be used with addEventListener event handler</p>
<p id="anonymousFuncOutput"></p>
<p id="namedFuncOutput"></p>
<button id="demoButton">Test it</button>
</body>
<script type="text/javascript"> document.getElementById("demoButton").addEventListener("click", function(){
document.getElementById("anonymousFuncOutput").innerHTML = "Output of anonymous function";
});
document.getElementById("demoButton").addEventListener("click", myNamedFunction);
function myNamedFunction() {
document.getElementById("namedFuncOutput").innerHTML = "Output of named function";
}
</script>
</html>
Output:
2. Multiple Events to the Same Element
We can add multiple event handlers to the same object of the DOM or equivalent event handler supporting example. We have already seen how the same element is assigned the same event with different executions or functions in the above example. The demo Button is assigned click event twice for anonymous and named function execution. We can even add different multiple events to the same object.
Code:
<!DOCTYPE html>
<html>
<body>
<p>These methods demonstrate that different multiple addEventListener event handlers can be defined for single element</p>
<p id="singleElement">Default Content</p>
<button id="demoButton">Test it</button>
</body>
<script type="text/javascript">
var demoButtonElement = document.getElementById("demoButton"); demoButtonElement.addEventListener("mouseover", mouseOverFunction); demoButtonElement.addEventListener("click", clickFunction); demoButtonElement.addEventListener("mouseout", mouseOutFunction);
function mouseOverFunction() {
document.getElementById("singleElement").innerHTML = "This element represents mouseOver event";
}
function clickFunction() {
document.getElementById("singleElement").innerHTML = "This element represents click event";
}
function mouseOutFunction() {
document.getElementById("singleElement").innerHTML = "This element represents mouseOut event";
}
</script>
</html>
Output:
When the program is run the first content of the singleElement paragraph is “Default Content”.
When the mouse is kept above the button then mouseOverFunction is called and the content of the singleElement changes from “Default Content” to “This element represents mouseOver event”.
When the mouse is taken out of singleElement button then the output seems somewhat like this:
When the final button with id singleElement is clicked then the method named clickFunction gets called as click event calls this method when this button is clicked.
3. Passing the Parameters
Passing the parameters to the function being called when the event occurs can only be done by calling a method which in turn will call another method with parameters. Example where addEventListener write and call an anonymous method inside which will be called the actual method whose execution I want to perform on event occurrence and pass the required parameters to it.
Code:
<!DOCTYPE html>
<html>
<body>
<p>These methods demonstrate how parameters can be passed in addEventListener by calling a method which in turn will call our desired method with parameters</p>
<p id="multipliedResult"></p>
<button id="demoButton">Test it</button>
</body>
<script type="text/javascript"> document.getElementById("demoButton").addEventListener("click", () => { multiplyNumbers(15, 27);
});
function multiplyNumbers(a, b) { var multipliedValue = a * b;
document.getElementById("multipliedResult").innerHTML = multipliedValue;
}
</script>
</html>
Output:
4. Event Bubbling and Capturing
Suppose there is a div element with id outerElement and paragraph p element inside the div outerElement with id innerElement. If we declare a click eventlistener on both and click the child element paragraph then which event will execute first, its parent division’s or the child itself is decided by third optional parameter to eventListener is a capture.
If it’s capturing then parent’s i.e div element’s event listener will be called while in case of bubbling child’s paragraph element’s event listener will be called first and then the other.
Conclusion
In this way, we can use multiple addEventListner on single elements and removeEventListener to clear the event listener which is added.