β‘
EPISODE 07
click Β· input Β· submit Β· delegation Β· preventDefault
Events
Respond to user actions: handle clicks, form input, submissions, and delegate events for dynamic lists. Stop default behaviors when needed.
eventsaddEventListenerdelegationform
Duration
β± About 2 hours
Level
π Beginner+
Prerequisite
π― js-06
OUTCOME
Build fully interactive forms and dynamic lists with event delegation
What you'll learn
- 1Attach handlers with addEventListener (not onclick)
- 2Read event.target and event.currentTarget correctly
- 3Use event delegation for dynamic content
- 4Cancel default behavior with preventDefault
1. addEventListener
javascript
const btn = document.querySelector("#go");
function handleClick(e) {
console.log("clicked", e.currentTarget);
}
btn.addEventListener("click", handleClick);
btn.removeEventListener("click", handleClick); // detachaddEventListener supports multiple listeners on the same element and lets you remove them later β onclick does not.
2. Form Input
javascript
const form = document.querySelector("#signup");
form.addEventListener("submit", (e) => {
e.preventDefault(); // do NOT navigate to action URL
const data = new FormData(form);
console.log(Object.fromEntries(data));
});
const input = document.querySelector("#search");
input.addEventListener("input", (e) => {
console.log(e.target.value);
});3. Event Delegation
Instead of attaching a listener to every <li>, attach one to the parent <ul> and inspect event.target.
javascript
document.querySelector("#tasks").addEventListener("click", (e) => {
const li = e.target.closest("li");
if (!li) return;
if (e.target.matches(".delete")) {
li.remove();
} else if (e.target.matches(".toggle")) {
li.classList.toggle("done");
}
});π‘
Delegation handles items added later automatically β perfect for dynamic lists.
4. Common Events
| Event | Fires when |
|---|---|
| click | Element is clicked |
| input | Form field value changes |
| change | Form field commits (blur / select change) |
| submit | Form is submitted |
| keydown / keyup | Keyboard interaction |
| mouseenter / mouseleave | Mouse enters/leaves (no bubbling) |
| focus / blur | Focus changes |
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β