beginner

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 clicked

  • dblclick - Element is double-clicked

  • mouseenter - Mouse enters element

  • mouseleave - Mouse leaves element

  • mousemove - Mouse moves over element
Keyboard Events:
  • keydown - Key is pressed

  • keyup - Key is released

  • keypress - Key produces character (deprecated)
Form Events:
  • submit - Form is submitted

  • input - Input value changes

  • change - Input loses focus after change

  • focus - Element receives focus

  • blur - Element loses focus
Basic Example:
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

JavaScript
// 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

JavaScript
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())

❓ Frequently Asked Questions

addEventListener allows multiple handlers, supports options (once, capture), and can be removed. onclick can only have one handler.
Arrow functions don't bind their own 'this', inheriting from outer scope. Regular functions bind 'this' to the element.
Use removeEventListener with the same event type and function reference. Anonymous functions cannot be removed.
An Event object containing details about what happened (target element, mouse position, key pressed, etc.).

🔗 Related Exercises