Event Listeners¶
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
Syntax¶
Example¶
You can also refer to an external named function:
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
Removing Listeners¶
You can remove an event listener using removeEventListener(). Note that this only works if you used a named function.
Common Events¶
click: User clicks.mouseover/mouseout: User hovers.keydown/keyup: Keyboard interaction.submit: Form submission.DOMContentLoaded: The DOM structure is fully loaded.
Why use this?
Using addEventListener separates your JavaScript from your HTML (Separation of Concerns), making your code cleaner and easier to maintain than onclick="...".