JavaScript Lesson 11: Events
Events are actions that happen in the browser — clicking, typing, scrolling, hovering. JavaScript responds to events to make pages interactive.
addEventListener — The Right Way
const button = document.querySelector("#myBtn");
// Add event listener
button.addEventListener("click", function() {
console.log("Button clicked!");
});
// Arrow function (cleaner)
button.addEventListener("click", () => {
console.log("Clicked with arrow function!");
});
// Separate named function (best for removing later)
function handleClick() {
console.log("Handled!");
}
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick); // remove
Common Events
const input = document.querySelector("input");
const form = document.querySelector("form");
// Mouse events
element.addEventListener("click", handler);
element.addEventListener("dblclick", handler);
element.addEventListener("mouseover", handler);
element.addEventListener("mouseout", handler);
// Keyboard events
document.addEventListener("keydown", (e) => {
console.log(e.key, e.code); // which key?
});
// Input events
input.addEventListener("input", (e) => {
console.log("Typed:", e.target.value);
});
// Form submit
form.addEventListener("submit", (e) => {
e.preventDefault(); // stop page reload!
console.log("Form submitted");
});
The Event Object
document.addEventListener("click", (event) => {
console.log(event.type); // "click"
console.log(event.target); // element clicked
console.log(event.clientX); // X position of click
console.log(event.clientY); // Y position of click
event.preventDefault(); // stop default action
event.stopPropagation(); // stop event bubbling
});
🏋️ Practice Task
Create an HTML page with an input field and a “live preview” div. As the user types in the input, immediately display what they type in the div (no button needed). Also add a character counter showing how many characters they have typed.
💡 Hint: Use addEventListener(“input”, …) on the input. Get the value with e.target.value. Update div.textContent.