Event Handler Functions
You'll learn: How to write and organize functions that respond to user interactions and browser events.
What Is an Event Handler Function?
An event handler function is simply a JavaScript function that runs when a specific event occurs. Think of it like a doorbell button: when pressed (the event), it triggers a chime inside your house (the handler function). Without the function to handle what happens, pressing the button would do nothing.
When you use addEventListener(), you pass it a function that contains the instructions for what should happen when that event fires.
Writing Handler Functions
There are two common patterns for creating event handlers:
// Pattern 1: Named function defined separately
function handleClick() {
console.log('Button was clicked!');
}
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
// Pattern 2: Anonymous function defined inline
button.addEventListener('click', function() {
console.log('Button was clicked!');
});
Both work identically. Named functions are easier to reuse and remove later, while inline functions keep related code together.
Organizing Your Handlers
As projects grow, organization matters:
// Group related handlers
function handleFormSubmit() {
// Submission logic
}
function handleInputChange() {
// Validation logic
}
// Attach them clearly
const form = document.querySelector('form');
const input = document.querySelector('input');
form.addEventListener('submit', handleFormSubmit);
input.addEventListener('input', handleInputChange);
Keep handler functions focused on one task. If they grow too large, break them into smaller helper functions.
Key Takeaway: Event handler functions are the "what happens next" part of events—write them clearly, name them descriptively, and keep them focused on a single responsibility.