By the end of this lesson, you will be able to attach JavaScript code to user actions such as clicks, key presses, and form submissions using event listeners.
What it is
An event is a signal that something has happened in the browser. User actions such as clicking a button, typing in an input, scrolling, or submitting a form create events. JavaScript can listen for those events and run a function when they occur.
The mental model is simple: an event source, such as a button, produces an event type, such as click. A listener is attached to the source, and when the event happens, the handler function runs. The handler receives an event object with details about what happened.
Related terms include event.target, event.currentTarget, addEventListener, removeEventListener, bubbling, and capturing.
Why it matters
- It lets web pages respond to users instead of only loading static content.
- It separates behavior from markup, making code easier to maintain.
- It supports multiple handlers for the same event on the same element.
- It enables common interactions such as buttons, menus, validation, and keyboard shortcuts.
- It works with event delegation, where one listener can handle events from many child elements.
Syntax or steps
- Select the element that should respond to the action.
- Choose the event type as a string, such as
"click","keydown", or"submit". - Write a handler function that runs when the event occurs.
- Attach the handler with
addEventListener.
The smallest useful pattern is:
element.addEventListener("click", handler);
Example
<button id="submit">Submit</button>
<script>
const btn = document.querySelector("#submit");
function handleClick(event) {
console.log("Button clicked:", event.type);
console.log("Clicked element:", event.target);
}
btn.addEventListener("click", handleClick);
</script>
Part-by-part explanation
document.querySelector("#submit")finds the button withid="submit".handleClickis the handler function. It receives aneventobject automatically.event.typeis the string"click".event.targetis the element that actually triggered the event.btn.addEventListener("click", handleClick)attaches the handler to the button. Notice thathandleClickis passed without parentheses, so it is not called immediately.
Common mistakes
- Calling the handler too early. Writing
btn.addEventListener("click", handleClick())runs the function immediately. Fix: pass the function name,handleClick. - Using the wrong event name. The event type is
"click", not"onclick", when usingaddEventListener. - Confusing
targetandcurrentTarget.event.targetis the deepest element that received the event.event.currentTargetis the element the listener is attached to. - Adding duplicate listeners. Calling
addEventListenermany times can attach the same handler repeatedly. UseremoveEventListenerwith the same function reference when needed.
When to use it
Use addEventListener for most JavaScript event handling. Compare it with the older on* property style:
| Approach | Best for | Limitation |
|---|---|---|
addEventListener |
Modern code, multiple handlers, capture options, and cleaner separation | Slightly more verbose |
onclick property |
Quick single handler or legacy code | Assigning a new handler overwrites the previous one |
Use addEventListener when you need reliable, flexible event handling. Use onclick only when a single handler is enough and you are working with simple or older code.
Practice
Guided exercise: Add a listener to an input so that pressing any key logs the key name.
const input = document.querySelector("input");
input.addEventListener("keydown", function (event) {
console.log("Key pressed:", event.key);
});
Expected output when the user presses a: Key pressed: a.
Challenge: Make a button toggle a class named active each time it is clicked. Hint: use event.target.classList.toggle("active") inside a click handler.
Quick check
Question: Why should you write btn.addEventListener("click", handleClick) instead of btn.addEventListener("click", handleClick())?
Answer: The first form passes the function itself to be called later when the event happens. The second form calls the function immediately and passes its return value as the handler.
Summary
Events connect user actions to JavaScript behavior. The core pattern is to select an element, choose an event type, and attach a handler with addEventListener. Once you understand the event object and the difference between target and currentTarget, you can build interactive pages with confidence.