HTML DOM EventListener


In JavaScript, an event listener is a function that waits for a specific event to occur and then triggers an action in response. An event listener is added to an HTML element or document object using the addEventListener() method.

The addEventListener() method takes two arguments: the type of event to listen for and the function to be executed when the event is triggered.

Example

Preview

The addEventListener() method is used to add a click event listener to a Button element with the ID of myButton. When the button is clicked, the anonymous function passed as the second argument will be executed, which in this case displays an alert message. Event listeners can also be removed from an HTML element using the removeEventListener() method.

This method takes the same two arguments as addEventListener(): the type of event to be removed and the function that was originally added as the event listener.

The setTimeout() method is used to remove the click event listener from the button element after 5 seconds. The ButtonClickHandler() function is passed as the second argument to both addEventListener() and removeEventListener() , so that it can be easily removed if not needed.

By using event listeners in combination with the various events available in the HTML DOM, you can create dynamic and interactive web pages that respond to user actions in real-time.

Example

Preview