Nearby lessons

10 of 14

JavaScript 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.

Example02
🧩Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🎯 Add an Event Handler to an Element

Attach a function to run when an event like click occurs on an element.

Example03
🧩Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

➕ 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.

Example04
🧩Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🌐 Add an Event Handler to the window Object

You can add listeners to global objects like window or document.

Example05
🧩Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

📦 Passing Parameters

You can't directly pass arguments to the function in addEventListener. Use an anonymous function or arrow function to do so.

Example06
🧩Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🔁 Event Bubbling or Event Capturing?

addEventListener() accepts a third optional argument: useCapture. Set it to true for capturing phase, or false (default) for bubbling.

Example07
🧩Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

❌ The removeEventListener() Method

You can remove a previously attached event listener using removeEventListener(). The function reference must match exactly.

Example08
🧩Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3