Curriculum / Intermediate / Lesson 20

Events

addEventListener, event objects, and event delegation.

20 of 30
intermediate 📖 7 min read 🎯 4 questions

What are Events?

Events are actions that happen in the browser — clicks, keypresses, mouse movements, form submissions, and more. JavaScript can listen for these events and respond to them.

💡 Key insight Events are at the heart of interactive web pages. Without events, web pages would be static documents.

Adding Event Listeners

The modern way to handle events is with addEventListener().

element.addEventListener('click', function() {
  console.log('Element clicked!');
});

// Using arrow functions
element.addEventListener('click', () => {
  console.log('Clicked!');
});

Common Event Types

The Event Object

When an event fires, JavaScript passes an event object to the handler with details about the event.

element.addEventListener('click', function(event) {
  console.log('Target:', event.target);
  console.log('Type:', event.type);
  console.log('X position:', event.clientX);
});

Event Delegation

Instead of attaching event listeners to many elements, attach one to a parent and use event bubbling.

document.getElementById('parent').addEventListener('click', function(event) {
  if (event.target.matches('.child')) {
    console.log('Child clicked!');
  }
});

Removing Event Listeners

function handler() { console.log('Clicked!'); }
element.addEventListener('click', handler);
element.removeEventListener('click', handler);

Common Mistakes

Quick Quiz

1. How do you add an event listener in modern JavaScript?

2. What does the event object contain?

3. What is event delegation?

4. Which property gives you the element that triggered the event?

Summary

Back to curriculum