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
- Mouse Events:
click,dblclick,mouseenter,mouseleave,mousemove - Keyboard Events:
keydown,keyup,keypress - Form Events:
submit,change,input,focus,blur - Window Events:
load,resize,scroll
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
- Using inline event handlers (
onclick="...") instead ofaddEventListener - Forgetting to remove event listeners (causes memory leaks)
- Using
event.targetwhen you meantevent.currentTarget - Not preventing default behavior when needed (
event.preventDefault())
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
- Events are actions that happen in the browser
- Use
addEventListener()to listen for events - Common events:
click,input,mouseenter,submit - The event object provides details about the event
- Event delegation uses event bubbling for efficiency
- Use
removeEventListener()to clean up listeners
