Event handler
An event handler is a function that runs when a specific event happens on a page, such as a click, a key press, a form submission or the mouse moving over an element. Handlers are how a static page becomes interactive: the browser detects the event and calls the function you attached to it.
Three ways to attach a handler
JavaScript has grown several ways to connect a function to an event:
- Inline HTML attributes, such as
<button onclick="save()">. This mixes behaviour into markup and is hard to maintain. - DOM properties, such as
button.onclick = save. Simple, but an element can hold only one handler per event this way; assigning again replaces the first. addEventListener, such asbutton.addEventListener('click', save). This is the recommended approach. It allows several handlers for the same event, supports options, and can be removed cleanly.
Using addEventListener and the event object
When the browser calls your handler, it passes an event object describing what happened. It includes event.type, event.target (the element where the event started), mouse coordinates, the key pressed, and methods like preventDefault().
<button id="like">Like</button>
<span id="count">0</span>
<input id="search" placeholder="Press Enter to search">
<script>
const likeBtn = document.getElementById('like');
const countEl = document.getElementById('count');
let likes = 0;
function handleLike(event) {
likes += 1;
countEl.textContent = likes;
console.log('Clicked:', event.target.id);
}
likeBtn.addEventListener('click', handleLike);
document.getElementById('search').addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
console.log('Searching for', e.target.value);
}
});
</script>
Notice that handleLike is passed without brackets. The browser needs the function itself so it can call it later.
Preventing default behaviour
Some events come with built-in browser actions: clicking a link navigates, submitting a form reloads the page, pressing a key types a character. Calling event.preventDefault() inside the handler cancels that default action, which is how you handle form submission with JavaScript instead of a full page reload.
The mistake of calling the function too early
A very common bug looks like this: likeBtn.addEventListener('click', handleLike()). The brackets run handleLike immediately when the line executes, and its return value (undefined) is registered as the handler. Nothing happens on click. If you need to pass extra arguments, wrap the call in an arrow function: addEventListener('click', () => handleLike(5)).
A second common bug is trying to attach a handler before the element exists. If your script runs in the <head>, getElementById returns null and the call throws. Place scripts at the end of <body> or use the defer attribute.
Removing handlers and useful options
removeEventListener must receive the exact same function reference that was added. An anonymous arrow function cannot be removed later, because you have no reference to it, so give handlers a name when you plan to remove them.
The third argument of addEventListener accepts options:
{ once: true }removes the handler automatically after it runs once.{ passive: true }promises you will not callpreventDefault, which helps scrolling performance for touch and wheel events.{ capture: true }runs the handler during the capture phase, which the next lesson on event flow explains.
Rule to take away: use addEventListener, pass the function without calling it, read details from the event object, and keep a named reference if you will need to remove it.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.