HAP studying and taking notes

The addEventListener Pattern

Quick Reference

Everything I learned about addEventListener at Station 1, organized for quick reference. The three-part pattern, callback styles, event types, and the mistakes that tripped me up. 🟠

← Back to Station 1: Listening

The Three-Part Pattern

1

Target

The DOM element you want to watch. Get it with document.querySelector(). This is the doorbell button.

2

Event Type

A string telling the browser what to listen for: 'click', 'submit', 'keydown'. Always in quotes. This is what kind of press activates the bell.

3

Callback

The function that runs when the event fires. Passed by reference (no parentheses). The browser stores it and invokes it later. This is the bell.

Syntax

The pattern:
// The addEventListener pattern
target.addEventListener(eventType, callback);

// Example with all three parts labeled:
const button = document.querySelector('.my-button');
//    ^^^^^^ — target (the DOM element)

button.addEventListener('click', handleClick);
//                       ^^^^^^  ^^^^^^^^^^^
//                       event   callback
//                       type    (function reference)

Callback Styles

Three ways to write the callback. All do the same thing — choose based on whether you need to reuse the function.

Three callback styles:
// Style 1: Named function (recommended for reuse)
function handleClick(event) {
  console.log('Clicked!', event.target);
}
button.addEventListener('click', handleClick);

// Style 2: Anonymous function (inline, one-time use)
button.addEventListener('click', function(event) {
  console.log('Clicked!', event.target);
});

// Style 3: Arrow function (concise, one-time use)
button.addEventListener('click', (event) => {
  console.log('Clicked!', event.target);
});

Common Event Types

🖱️

Mouse Events

'click' — mouse click or tap. 'dblclick' — double click. 'mouseover' / 'mouseout' — hover enter/leave.

⌨️

Keyboard Events

'keydown' — key pressed. 'keyup' — key released. Use event.key to check which key (covered in Station 2).

📝

Form Events

'submit' — form submitted (listen on the form element, not the button). 'change' — dropdown or checkbox changed. 'input' — text typed in a field.

🔄

Focus Events

'focus' — element receives focus. 'blur' — element loses focus. Useful for form validation as a user moves between fields.

Common Mistakes

Mistakes I made (so you do not have to):
// MISTAKE: Calling the function instead of passing it
button.addEventListener('click', handleClick());
//                                          ^^
// Runs immediately, passes return value (undefined)

// CORRECT: Pass the function reference
button.addEventListener('click', handleClick);

// MISTAKE: Forgetting quotes on event type
button.addEventListener(click, handleClick);
//                      ^^^^^ — not a string!

// CORRECT: Event type is always a string
button.addEventListener('click', handleClick);

← Back to Station 1: Listening