The addEventListener method in JavaScript is used to attach an event listener to an HTML element.
It provides a flexible way to handle various events, including click, double-click, keypress, and many others.
Here's a general syntax for using addEventListener:
element.addEventListener(eventType, callbackFunction [, useCapture]);
element: The HTML element to which the event listener is attached.
eventType: A string representing the type of the event (e.g., "click", "dblclick", "keydown").
callbackFunction: The function that will be executed when the event occurs.
useCapture (optional): A boolean value indicating whether to use the capturing phase (true) or the bubbling phase (false). Default is false (bubbling phase).
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>addEventListener Example</title> </head> <body> <button id="yourButton">Click me</button> <script> // Select the button element const button = document.getElementById('yourButton'); // Define the callback function for the click event function handleClick() { alert('Button clicked!'); } // Attach the event listener to the button button.addEventListener('click', handleClick); </script> </body> </html>
The HTML file contains a button element with the ID `yourButton`.
The JavaScript code selects the button using document.getElementById('yourButton').
It defines a function handleClick that will be executed when the button is clicked.
The addEventListener method is used to attach the click event listener to the button, specifying the event type and the callback function.