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.

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🎯 Add an Event Handler to an Element

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

➕ 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
PREVIEW READY
Loading Editor...
Live Preview

🌐 Add an Event Handler to the window Object

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

📦 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
PREVIEW READY
Loading Editor...
Live Preview

🔁 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
PREVIEW READY
Loading Editor...
Live Preview

❌ The removeEventListener() Method

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

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!JavaScript DOM Navigation