11. Event Handling in JavaScript
What Are Events?
Events are signals that something has happened — like a button being clicked, a key being pressed, or the page finishing loading. JavaScript can listen for these events and respond to them.
<button id="greetBtn">Say Hello</button>const button = document.getElementById("greetBtn");
button.addEventListener("click", () => {
alert("Hello there!");
});Common Event Types
- `click` — When an element is clicked
- `mouseover` and `mouseout` — When the mouse enters or leaves an element
- `keydown` and `keyup` — When a key is pressed or released
- `submit` — When a form is submitted
- `input` — When a form input changes
Event Object
Every event handler receives an `event` object with useful details like the target element, mouse position, or key pressed.
button.addEventListener("click", (event) => {
console.log(event.target); // Logs the clicked element
});Event Bubbling and Capturing
Events flow through the DOM in two phases: **capturing** (top-down) and **bubbling** (bottom-up). By default, most listeners trigger during bubbling — when the event reaches the target and travels upward.
<div id="parent">
<button id="child">Click me</button>
</div>document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked!");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked!");
});If you click the button, both messages appear — first for the child, then the parent (bubbling upward).
Stopping Propagation
To prevent the event from bubbling up to parent elements, use `event.stopPropagation()`.
child.addEventListener("click", (event) => {
event.stopPropagation();
console.log("Only the child reacts now.");
});Event Delegation
Instead of adding listeners to multiple child elements, you can add one listener to a parent and use event delegation to handle them efficiently.
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>const menu = document.getElementById("menu");
menu.addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
console.log(`${event.target.textContent} clicked!`);
}
});Mini Challenge
Create a list of buttons that change the background color of the page when clicked. Use event delegation so you only attach **one** event listener to their parent container.
Key Takeaway
Events are how you make websites interactive. Understanding event bubbling and delegation helps you write efficient, powerful code that responds to user actions with ease.