Nearby lessons
10 of 14JavaScript HTML DOM EventListener
📌 What is DOM EventListener?
The addEventListener() method lets you attach one or more event handlers to a single element without overwriting existing ones. It's a cleaner and more flexible way to handle user events like clicks, focus, keypresses, and more.
📌 The addEventListener() Method
addEventListener() attaches an event handler to a specified element.
Code Example
🎯 Add an Event Handler to an Element
Attach a function to run when an event like click occurs on an element.
Code Example
➕ Add Many Event Handlers to the Same Element
You can attach multiple event listeners of the same type to a single element without overwriting previous ones.
Code Example
🌐 Add an Event Handler to the window Object
You can add listeners to global objects like window or document.
Code Example
📦 Passing Parameters
You can't directly pass arguments to the function in addEventListener. Use an anonymous function or arrow function to do so.
Code Example
🔁 Event Bubbling or Event Capturing?
addEventListener() accepts a third optional argument: useCapture. Set it to true for capturing phase, or false (default) for bubbling.
Code Example
❌ The removeEventListener() Method
You can remove a previously attached event listener using removeEventListener(). The function reference must match exactly.