Events & Listeners
Make your website interactive by listening to user actions. Learn how to capture clicks, keystrokes, and the powerful Event Object.
Waiting for the User
A webpage is static until the user does something: clicking a button, scrolling the page, or typing in a field.
The browser broadcasts these actions as **Events**. As a developer, you can write JavaScript functions that "listen" for these events and execute code in response.
addEventListener
The modern standard for capturing events is the addEventListener() method.
It takes two primary arguments: the type of event you are listening for (like 'click'), and the callback function to run when it happens: button.addEventListener('click', () => { console.log('Clicked!'); });
The Event Object
When an event fires, the browser doesn't just run your function; it passes a massive object full of data into your function. This is the **Event Object**.
If you define a parameter in your callback (usually named e or event), you can access this data:
- e.type: The type of event (e.g., 'click').
- e.target: The exact DOM element the user interacted with.
- e.clientX / e.clientY: The exact pixel coordinates of the mouse.
The Event Inspector
Interact with the Target Pad below (click, double-click, or hover). Watch how the browser instantly generates a detailed Event Object containing data about your specific interaction.
The Event Inspector
console.log(e.target); // Who triggered it?
console.log(e.clientX); // Mouse X coordinate
console.log(e.clientY); // Mouse Y coordinate
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use
addEventListener()to attach JavaScript logic to user interactions. - The browser automatically passes an
Eventobject to your callback function. e.targetgives you the exact DOM element that fired the event.e.preventDefault()stops built-in HTML behaviors (like links navigating or forms submitting).- Failing to use
removeEventListener()on deleted nodes causes memory leaks.
Done with this concept?
Mark it complete to track your progress. No login needed.