In JavaScript, you can add event listeners to DOM elements using the addEventListener
method.
The addEventListener
method allows you to specify a function (known as an event handler) that will be executed when a specific event occurs on the DOM element.
Syntax for adding an event listener:
element.addEventListener(eventType, eventHandler);
where element
is the DOM element to which you want to add the event listener, eventType
is a string representing the type of event you want to listen for (e.g., “click”, “keydown”, “change”, etc.), and eventHandler
is the function that will be executed when the event occurs.
Example:
Here’s an example of adding an event listener for a “click” event:
const button = document.getElementById("myButton"); // Get the DOM element by its ID
button.addEventListener("click", function () {
// Add event listener for "click" event
console.log("Button clicked!"); // Event handler function
});
In this example, the button
element is selected using getElementById
method, and then an event listener is added using addEventListener
to listen for the “click” event. When the button is clicked, the event handler function (in this case, an anonymous function) will be executed, which logs a message to the console.
Note:
Note that you can also remove event listeners using the removeEventListener
method by passing the same event type and event handler function that was used when adding the event listener. This can be useful if you want to remove an event listener from a DOM element after it has been added.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.