The browser fires **events** for user actions, network requests, timers, and more. **addEventListener** is the standard way to subscribe to events. The **event object** passed to handlers contains details (target, type, coordinates for mouse events, key for keyboard events). Events **bubble** up the DOM tree by default.
1Understanding DOM Events
The browser fires events for user actions, network requests, timers, and more. addEventListener is the standard way to subscribe to events. The event object passed to handlers contains details (target, type, coordinates for mouse events, key for keyboard events). Events bubble up the DOM tree by default.
Always use addEventListener instead of on-properties (onclick) — it allows multiple listeners and is easier to remove.
const btn = document.querySelector('#submitBtn');
function handleClick(event) {
event.preventDefault(); // stop form submit
console.log('Button clicked by:', event.target.id);
console.log('Modifier keys:', { shift: event.shiftKey, ctrl: event.ctrlKey });
}
btn.addEventListener('click', handleClick);
// Later: remove it
btn.removeEventListener('click', handleClick);2Practical Example
Here is a real-world application of DOM Events showing how it is used in production JavaScript code.
// Event bubbling
document.addEventListener('click', (e) => {
console.log('Document received click from:', e.target.tagName);
});
// Clicking a <button> logs: 'Document received click from: BUTTON'
// because the event bubbles up through the DOM3Best Practices
Follow these guidelines when working with DOM Events:
1. Always use addEventListener, not onclick attributes
2. Use removeEventListener with the same function reference to clean up
3. Use event.preventDefault() to stop default browser behavior
Tip: Always use addEventListener instead of on-properties (onclick) — it allows multiple listeners and is easier to remove.
const btn = document.querySelector('#submitBtn');
function handleClick(event) {
event.preventDefault(); // stop form submit
console.log('Button clicked by:', event.target.id);
console.log('Modifier keys:', { shift: event.shiftKey, ctrl: event.ctrlKey });
}
btn.addEventListener('click', handleClick);
// Later: remove it
btn.removeEventListener('click', handleClick);