Concept Explanation
Events are "Signals" that something happened. A user clicked a button, scrolled the page, or pressed a key. JavaScript "Listens" for these signals using Event Listeners.
A key concept is Event Bubbling. If you click a button inside a div, the click "bubbles up" from the button to the div, then to the body, and finally the document.
Syntax or Core Structure
The addEventListener Pattern
This is the ONLY way you should handle events in modern apps.
const btn = document.querySelector("button");
btn.addEventListener("click", (event) => {
console.log("Button clicked!");
console.log(event.target); // The specific element clicked
});
Stopping the Bubble
event.stopPropagation(); // Prevents the event from reaching parent elements
event.preventDefault(); // Prevents default behavior (like a link opening)
Real World Example
The "Load More" Button: When you click the button, an event listener triggers a function that fetches more data from a server and appends it to the DOM.
Common Mistakes
- Multiple Listeners: If you add the same listener 10 times in a loop, it will run 10 times for every single click!
- Memory Leaks: Forgetting to
removeEventListenerwhen an element is deleted can slow down your app over time. - Inline Handlers: Never use
onclick="doSomething()"in your HTML. It mixes logic with structure and is very hard to maintain.
Practice Exercises
- The Double Clicker: Add an event listener that only triggers when a user DOUBLE clicks an image.
- The Key Logger: Create a script that logs every key the user presses while they are typing in a text field.
- The Preventer: Create a link to "google.com" but use
preventDefault()to make it do nothing when clicked.