Lesson 23: Event Listeners
π§² Lesson 23: DOM Event Listeners
Your website shouldnβt just sit there like a rock. It should react to what users do β clicks, typing, scrolling, submitting forms, and more. This is where event listeners come in.
π What is an Event Listener?
An event listener is a function that waits for something to happen β like a button click β and then runs some code in response.
β Basic Syntax
const button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Button clicked!");
});
This waits for the click event on the button. When it happens, it shows an alert.
π§ Anatomy of addEventListener()
"click"β the type of event to listen forfunction() { ... }β the code to run (the event handler)
βοΈ Types of Events
Here are just a few youβll use often:
clickβ user clicks an elementsubmitβ form is submittedinputβ user types into a fieldkeydownβ a key is pressedmouseoverβ cursor hovers over an element
π― Named Function vs Anonymous
You can pass a named function to reuse it:
function handleClick() {
console.log("Clicked!");
}
button.addEventListener("click", handleClick);
Or use an arrow function:
button.addEventListener("click", () => {
console.log("Arrow function click!");
});
π Real-World Example: Form Submit
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault(); // Prevent form from refreshing the page
console.log("Form submitted!");
});
Notice e.preventDefault() β it stops the default action (e.g., reloading the page).
π‘ Best Practices
- Use
addEventListenerinstead ofonclickβ it's cleaner and more flexible - Always remove listeners if you're adding them repeatedly
- Use arrow functions to avoid hoisting issues with
this
You're now ready to make your website respond to clicks, form entries, key presses, and more. Next up, weβll explore how to handle forms and user input like a boss.