JavaScript Events

JavaScript
const btn = document.querySelector("button");
btn.addEventListener("click", (event) => {
    console.log("Clicked!", event.target);
});
CategoryEvents
Mouseclick, dblclick, mouseover, mouseout, mousemove
Keyboardkeydown, keyup
Formsubmit, input, change, focus, blur
Windowload, DOMContentLoaded, resize, scroll

Form Validation

JavaScript
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:

JavaScript
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