Events in JavaScript

Learn to handle user interactions with event listeners.

What are Events?

Events are actions that happen in the browser - clicks, key presses, mouse movements, form submissions, and more. JavaScript can detect and respond to these events.

Key Concept: Events make your web pages interactive. They're the bridge between user actions and JavaScript code.

Adding Event Listeners

The addEventListener method is the modern way to handle events.

JavaScript
// Syntax: element.addEventListener(event, callback)

const button = document.querySelector('button');

button.addEventListener('click', function() {
    console.log('Button was clicked!');
});

// With arrow function
button.addEventListener('click', () => {
    console.log('Clicked!');
});
Try it yourself
Output

The Event Object

Event handlers receive an event object with useful information about the event.

Try it yourself
Output

Interactive Demo

Try interacting with these elements to see events in action:

Event Bubbling and Capturing

Events propagate through the DOM tree. Understanding this is crucial for complex applications.

Try it yourself
Output

Event Delegation

Instead of adding listeners to many elements, add one to a parent and use the event object to determine the target.

Try it yourself
Output

Preventing Default Behavior

Try it yourself
Output

Removing Event Listeners

Try it yourself
Output

Challenge: Keyboard Shortcuts

Describe how you would create keyboard shortcuts for a web app. What events would you use? How would you detect modifier keys?

Your solution
Output