addEventListener()
The addEventListener() method attaches an event handler to the specified element. Any number of event handlers can be added to a single element without overwriting existing event handlers.
Syntax:
element.addEventListener(event, listener, useCapture);
Parameters:
- event: Event can be any valid JavaScript event. Events are used without the “on” prefix like using “click” instead of “onclick” or “mousedown” instead of “onmousedown”.
- listener(handler function): It can be a JavaScript function that responds to the event that occurs.
- useCapture: (Optional parameter) A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
Note: The addEventListener() method can have multiple event handlers applied to the same element. It doesn’t overwrite other event handlers.
Example: Below is a JavaScript code to show that multiple events are associated with an element and there is no overwriting.
HTML
< body > < button id = "btn" >Click here</ button > < h1 id = "text1" ></ h1 > < h1 id = "text2" ></ h1 > < script > let btn_element = document.getElementById("btn"); btn_element.addEventListener("click", () => { document.getElementById("text1") .innerHTML = "Task 1 is performed"; }) btn_element.addEventListener("click", () => { document.getElementById("text2") .innerHTML = "Task 2 is performed"; }); </ script > </ body > |
Output:
Difference between addEventListener and onclick in JavaScript
The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked. However, they are not the same. In this article, we are going to understand the differences between them.