JavaScript Events
const btn = document.querySelector("button");
btn.addEventListener("click", (event) => {
console.log("Clicked!", event.target);
});
| Category | Events |
|---|---|
| Mouse | click, dblclick, mouseover, mouseout, mousemove |
| Keyboard | keydown, keyup |
| Form | submit, input, change, focus, blur |
| Window | load, DOMContentLoaded, resize, scroll |
Form Validation
document.querySelector("form").addEventListener("submit", (e) => {
const email = e.target.email.value;
if (!email.includes("@")) {
e.preventDefault(); // stop the form from submitting
alert("Please enter a valid email");
}
});
Bubbling and Delegation
Events bubble up from the target element to its ancestors. Event delegation puts one listener on a parent instead of one on every child:
document.querySelector("#list").addEventListener("click", (e) => {
if (e.target.tagName === "LI") e.target.classList.toggle("done");
});
Call e.stopPropagation() to stop bubbling.
Track your progress through the JavaScript course