Attach an event listener that triggers when a user clicks a button.
document.getElementById(“myBtn”).addEventListener(“click”, displayDate); |
The addEventListener() method attaches an event handler to a specified element without replacing any existing event handlers.
It allows you to add multiple event handlers to a single element, including multiple handlers of the same type (e.g., two “click” events).
Event listeners can be added to any DOM object, including window
, offering better control over event bubbling, improved readability, and easy removal with removeEventListener()
.
element.addEventListener(event, function, useCapture); |
The first parameter specifies the event type, the second is the callback function, and the third optional boolean sets event bubbling or capturing.
Note that the “on” prefix is not used for the event; you should use “click” instead of “onclick”. |