Updated June 15, 2023
Introduction to addEventListener JavaScript
The EventTarget interface provides multiple methods for handling the events in javascript on DOM objects. One of the essential methods of the EventTarget interface is addEventListener() helps create and define the snippet execution on the event’s occurrence. These events can also be defined on event-supporting objects like AudioNode, AudioContext, and XMLHttpRequest.
It is very easy to add an event to any object in javascript using addEventListener(). We can even add multiple event listeners to a single object 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: Any element in the 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 click, dbclick, mouseover, mousemove, etc. Caution should be taken while selecting 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 event mentioned above occurs. This function can be either named or anonymous. We will see the example of both of these methods of declaring functions in the further part.
- useCapture: This is a Boolean parameter that 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 the event execution type, we can send this parameter as true, while in all other cases, it will show a bubbling type of nature during event execution. We will see this working and the difference between them clearly with the help of examples.
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 that 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’ve already demonstrated assigning the same event with different executions or functions to the same element in the example above. We assign the demo Button a click event twice to execute both anonymous and named functions. We can even add multiple different 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 you run the program, the singleElement paragraph displays “Default Content” as its first content.
When you hover the mouse over the button, it calls the mouseOverFunction, changing the content of the singleElement from “Default Content” to “This element represents mouseOver event.
When the mouse is taken out of the singleElement button, then the output seems somewhat like this:
When you click the final button with the id ‘singleElement,’ it triggers the ‘clickFunction’ method because the click event calls this method.
3. Passing the Parameters
You can only pass parameters to the function when the event occurs by calling a method that then calls another method with parameters. When an event occurs, it triggers an anonymous method which then calls the actual method you want to execute. This way, you can also pass any necessary parameters to the method.
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. The eventListener determines the order of execution between the parent and child element when we attach a click eventlistener to both by using the optional parameter capture.
In the case of capturing, the event listener of the parent (i.e., the div element) will be called. However, in the case of bubbling, the event listener of the child’s paragraph element will be called first, followed by the others.
Conclusion
This way, we can use multiple addEventListner on single elements and removeEventListener to clear the added listener.
Recommended Articles
This is a guide to addEventListener JavaScript. Here we discuss the introduction and examples of addEventListener JavaScript. You may also have a look at the following articles to learn more –