Handling with addEventListener

This is the best way to handle an event because you can also remove the associated handlers using the method removeEventListener.

Syntax:

element.addEventListener("event name" , callback , useCapture)
element.removeEventListener("event name" , callback , useCapture)
  • event name: It is the name of the event.
  • callback: It is a function that gets triggered when an event occurs.
  • useCapture: A boolean value [Capture: true | Bubble: false] – represents the order in which the listener gets triggered when the events are added in a hierarchy.

There are two types of the above listener.

  • Capture: Here the parent of the element gets more priority than the actual element where the event takes place.
  • Bubble: Here the actual element where the event takes place gets more priority than its parent.

Example: Here, we are able to print a message on the screen with the click of a button with the help of event handlers.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>EventHandlers</title>
</head>
 
<body>
    <div class="buttons">
        <button>Press me</button>
    </div>
    <script>
        const buttonContainer = document.querySelector('.buttons');
        buttonContainer.addEventListener('click', event => {
            document.write('<h1 style="color:green">
                w3wiki</h1>');
        })
    </script>
</body>
 
</html>


Output:

 

Explain about EventHandler with Example

Event handlers are the properties in the browser or DOM API that handles the response to an event. Let us understand this with an example when we click on any virtual button of the browser a particular task gets executed for us, and eventually, the browser responds to your trigger with some result, or when you hover on a browser component it gets disguised by changing its display properties. This happens with event handlers. Event handlers help you to reflect on an event occurrence.

Similar Reads

Different ways of handling an event in Javacript

There are three ways of handling an event or you can say that there are three types of event handlers...

Handling with addEventListener

This is the best way to handle an event because you can also remove the associated handlers using the method removeEventListener....

Handling with object method

...

Handling with HTML inline attribute

Every element in the DOM contains some methods like onclick, ondrag, onkeypress, etc. which can be used to handle the event. You can pass a function to this method which takes the event object a parameter....