Event Listener Basics
Add event listeners to handle user interactions.
Event listeners enable user interaction in web applications. This exercise teaches you how to respond to user actions, handle events properly, and build interactive interfaces.
📚 Concepts & Theory
Event listeners are the foundation of interactive web applications. They allow JavaScript to respond to user actions like clicks, key presses, and mouse movements.
Understanding Event Listeners:
Basic Syntax:
element.addEventListener(eventType, handlerFunction);
Common Events:
Mouse Events:
click- Element is clickeddblclick- Element is double-clickedmouseenter- Mouse enters elementmouseleave- Mouse leaves elementmousemove- Mouse moves over element
keydown- Key is pressedkeyup- Key is releasedkeypress- Key produces character (deprecated)
submit- Form is submittedinput- Input value changeschange- Input loses focus after changefocus- Element receives focusblur- Element loses focus
const button = document.querySelector("button");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
Arrow Function Syntax:
button.addEventListener("click", () => {
console.log("Clicked!");
});
Event Object:
button.addEventListener("click", (event) => {
console.log(event.target); // Element that triggered event
console.log(event.type); // Event type ("click")
console.log(event.clientX); // Mouse X coordinate
});
Removing Event Listeners:
function handler() {
console.log("Clicked");
}
button.addEventListener("click", handler);
button.removeEventListener("click", handler);
// Must use same function reference
Multiple Event Listeners:
// All will execute
button.addEventListener("click", handler1);
button.addEventListener("click", handler2);
button.addEventListener("click", handler3);
Event Propagation:
Bubbling (default):
// Event bubbles up from target to ancestors
child.addEventListener("click", () => {});
parent.addEventListener("click", () => {}); // Also fires
Capturing:
parent.addEventListener("click", handler, {capture: true});
Stop Propagation:
button.addEventListener("click", (e) => {
e.stopPropagation(); // Prevents bubbling
});
Event Delegation Pattern:
// Instead of adding listeners to many items:
parent.addEventListener("click", (e) => {
if (e.target.matches(".item")) {
// Handle item click
}
});
Modern Options:
element.addEventListener("click", handler, {
once: true, // Auto-remove after first trigger
passive: true, // Improves scroll performance
capture: false // Use bubbling (default)
}); 🎯 Your Challenge
Add a click listener that shows an alert.
📝 Starter Code
// HTML: <button id="alertBtn">Alert</button>
function setupListener() {
// Your code here
}
- Use addEventListener() method on the element
- First argument is the event type as a string
- Second argument is the function to execute
- Don't call the function - pass the function reference
- Syntax: element.addEventListener('click', functionName)
Solution
function setupListener() {
const btn = document.getElementById('alertBtn');
btn.addEventListener('click', function() {
alert('Button clicked!');
});
}
setupListener();
Explanation
This solution uses addEventListener() to attach a click event handler to an element. The method takes two arguments: the event type ("click") and a callback function that executes when the event occurs. addEventListener() is preferred over inline onclick attributes because: 1) it allows multiple handlers for the same event, 2) it supports event options like once and capture, 3) it separates JavaScript from HTML (better maintainability), 4) handlers can be removed with removeEventListener(). The callback receives an event object with details about what happened.
⚠️ Common Mistakes to Avoid
- Using inline onclick instead of addEventListener
- Calling the function instead of passing it (handler() vs handler)
- Anonymous functions can't be removed with removeEventListener
- Forgetting to check if element exists
- Not preventing default behavior when needed (e.preventDefault())