HTML DOM addEventListener() Method: This method attaches an event handler to the document.
document.addEventListener(event, function, useCapture)
- event: It is required parameter. It specifies the string which is name of the event.
- function: It is required parameter. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type of the event object depends on the defined event. For example, the “click” event is of MouseEvent object.
- useCapture: It is optional parameter. It specifies the boolean value that whether the event should be executed in the capturing or in the bubbling phase.
- true: It specifies that the event should execute in the capturing phase.
- false: It specifies that the event should execute in the bubbling phase.
- Parameters: It does not accept any parameter.
Example 1: This example disable the right click by adding an event listener for the “contextmenu” event and calling the preventDefault() method.
Example 2: This example disables the right-click on the image by adding an event listener for the “contextmenu” event and calling the preventDefault() method. Because, Sometimes we do not want the user to save the image.