The Three-Part Pattern
Target
The DOM element you want to watch. Get it with document.querySelector(). This is the doorbell button.
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.
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 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.
// 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
// 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);