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.
Adding Event Listeners
The addEventListener method is the modern way to handle events.
// 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!');
});
The Event Object
Event handlers receive an event object with useful information about the event.
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.
Event Delegation
Instead of adding listeners to many elements, add one to a parent and use the event object to determine the target.
Preventing Default Behavior
Removing Event Listeners
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?