About Lesson
Event Listener
An EventListener is a function that listens for a specified event on an element and triggers a callback function when that event occurs.
1. Adding Event Listeners with addEventListener()
addEventListener() is the primary method for listening to events. It allows you to attach an event to an element and define the action to take when the event occurs.
Syntax:
JavaScript
element.addEventListener("eventType", callbackFunction);
- eventType: The type of event (e.g., click, submit).
- callbackFunction: The function that executes when the event occurs.
Example:
JavaScript
let button = document.querySelector("#myButton");
button.addEventListener("click", function() {
alert("Button was clicked!");
});
Here, an event listener is added to button. When the button is clicked, an alert box appears with the message “Button was clicked!”.
Benefits of addEventListener()
- Multiple listeners: You can add more than one event listener to an element for the same event type.
- Flexible handling: You can use functions as callbacks directly or separately as standalone functions.
- Control over event phases: You can specify whether the listener triggers during the capture or bubble phase.