JavaScript Events & Interactivity
JavaScript Events are the backbone of web interactivity. Without events, our web pages are just static documents. Events allow our code to listen for user interactions and react accordingly.
The Event Listener
To capture an event, we use the methodaddEventListener(). It takes two main arguments: the type of event to listen for (like 'click'), and a callback function that runs when the event fires.
Common Event Types
We divide events into categories based on user interaction:
- Mouse:
click,dblclick,mouseenter,mouseleave - Keyboard:
keydown,keyup - Form:
submit,change,input
The Event Object & Prevention
Every time an event is triggered, the browser passes an Event Object to the callback function. This object contains data about the event, such as what key was pressed (e.key) or exactly where the mouse was (e.clientX).
Crucially, we use e.preventDefault() to stop the browser's default behavior. The most common use case is stopping a <form> from reloading the page when the user hits submit.
Event Propagation (Bubbling)
When an element is clicked, that event doesn't just stop at the element. It "bubbles" up the DOM tree, triggering any click listeners attached to its parent elements. You can stop this flow using e.stopPropagation().
View Deep Dive: Event Delegation+
Event Delegation is a technique where you attach a single event listener to a parent element, to listen for events firing on its children. Because events bubble up, the parent catches the event, and you can inspect `e.target` to figure out exactly which child was clicked. This is vastly more memory-efficient than attaching 1,000 listeners to 1,000 list items.
