JavaScript — Lesson 5
Events & Interactivity
Responding to user actions with events.
Events & Interactivity
Events are actions that happen in the browser - clicks, keypresses, mouse movements, form submissions, and more. JavaScript can listen for and respond to events.
Common Events
// Click
document.querySelector("button")
.addEventListener("click", () => { ... });
// Mouse hover
element.addEventListener("mouseenter", () => { ... });
element.addEventListener("mouseleave", () => { ... });
// Keyboard
document.addEventListener("keydown", (e) => {
console.log("Key pressed:", e.key);
});
// Form submit
form.addEventListener("submit", (e) => {
e.preventDefault(); // Stop page reload
console.log("Form submitted!");
});
// Input change
input.addEventListener("input", () => {
console.log("Value:", input.value);
});
The Event Object
Event listeners receive an event object e with useful properties and methods.
button.addEventListener("click", (e) => {
console.log(e.target); // The element clicked
console.log(e.clientX); // Mouse X position
console.log(e.clientY); // Mouse Y position
e.preventDefault(); // Prevent default behavior
e.stopPropagation(); // Stop event bubbling
});
Interactive Example: Counter
<button id="counterBtn">0 clicks</button>
<script>
let count = 0;
const btn = document.getElementById("counterBtn");
btn.addEventListener("click", () => {
count++;
btn.textContent = count + " clicks";
});
</script>
Event Delegation
Instead of adding listeners to many elements, add one to a parent and use e.target to identify the child.
document.querySelector("ul")
.addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
console.log("Clicked:", e.target.textContent);
}
});
Tip: Use event delegation when you have many similar elements (like list items or table rows) - it's more efficient and works for dynamically added elements.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →