JavaScript Fundamentals
JavaScript Events
JavaScript Events
Section titled “JavaScript Events”Events allow you to respond to user actions like clicks, key presses, and form submissions.
Adding Event Listeners
Section titled “Adding Event Listeners”const button = document.querySelector("#myButton");
button.addEventListener("click", function(event) { console.log("Button clicked!");});
// Arrow functionbutton.addEventListener("click", (e) => { console.log("Clicked at:", e.clientX, e.clientY);});Common Events
Section titled “Common Events”Mouse Events
Section titled “Mouse Events”element.addEventListener("click", handler);element.addEventListener("dblclick", handler);element.addEventListener("mouseenter", handler);element.addEventListener("mouseleave", handler);element.addEventListener("mousemove", handler);Keyboard Events
Section titled “Keyboard Events”document.addEventListener("keydown", (e) => { console.log("Key pressed:", e.key); if (e.key === "Enter") { // Handle Enter key }});
document.addEventListener("keyup", handler);Form Events
Section titled “Form Events”form.addEventListener("submit", (e) => { e.preventDefault(); // Prevent form submission const formData = new FormData(form); console.log(formData.get("username"));});
input.addEventListener("input", (e) => { console.log("Value:", e.target.value);});
input.addEventListener("change", handler);input.addEventListener("focus", handler);input.addEventListener("blur", handler);Event Object
Section titled “Event Object”element.addEventListener("click", (event) => { event.target; // Element that triggered event event.currentTarget; // Element with listener event.type; // Event type ("click") event.preventDefault(); // Prevent default action event.stopPropagation(); // Stop bubbling});Event Delegation
Section titled “Event Delegation”// Instead of adding listeners to each button...document.querySelector("#container").addEventListener("click", (e) => { if (e.target.matches(".btn")) { console.log("Button clicked:", e.target.textContent); }});Removing Event Listeners
Section titled “Removing Event Listeners”function handleClick() { console.log("Clicked!");}
button.addEventListener("click", handleClick);button.removeEventListener("click", handleClick);Next Steps
Section titled “Next Steps”Continue to Async JavaScript →
Tutorials