JavaScript Event Listeners: Click, Submit, Scroll and Delegation
An event listener is a function the browser calls when something happens to an element, such as a click, a form submit or a scroll. You attach one with element.addEventListener(type, handler, options). The options object turns on once, passive, capture or an abort signal, and removeEventListener detaches the same function again later.
| Option | Default | Effect |
|---|---|---|
| once | false | Removes the listener automatically after its first call |
| passive | false (true for wheel and touch on window, document and body) | Promises not to call preventDefault, so scrolling never waits |
| capture | false | Runs on the way down to the target instead of on the way back up |
| signal | none | An AbortSignal; aborting it removes the listener |
Updated
Events are easier to understand when you can see them. The event log below records every listener call on a small test area, so you can click, type, submit and scroll and watch the order, the target and the effect of each option. Then copy the patterns for the jobs you actually have.
Live event log
Click, type, submit and scroll in the test area. Every listener call is written to the log with its type, target and current target.
Event types you will use most
| Event | Fires when | Bubbles? |
|---|---|---|
| click | A pointer press and release, or Enter or Space on a button | Yes |
| input | The value of a field changes as the visitor types | Yes |
| change | A field's value is committed, for example on blur or selection | Yes |
| submit | A form is submitted; fires on the form element | Yes |
| keydown | A key is pressed | Yes |
| focus / blur | An element gains or loses focus | No |
| focusin / focusout | Same as focus and blur, but bubbling | Yes |
| DOMContentLoaded | The HTML is parsed and deferred scripts have run; listen on document | Not relevant |
Copyable patterns
Click with a named handler you can remove
Keeping the function in a variable is what makes removeEventListener work.
const button = document.querySelector("#menu-button");
function toggleMenu() {
const open = button.getAttribute("aria-expanded") === "true";
button.setAttribute("aria-expanded", String(!open));
}
button.addEventListener("click", toggleMenu);
// later
button.removeEventListener("click", toggleMenu);Handle a form submit without a reload
preventDefault stops the browser's own navigation. event.submitter tells you which submit button was used.
const form = document.querySelector("#signup");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const data = new FormData(form);
const status = form.querySelector("[role=status]");
status.textContent = "Sending...";
try {
const res = await fetch(form.action, { method: "POST", body: data });
status.textContent = res.ok ? "Thanks, you are on the list." : "Something went wrong.";
} catch {
status.textContent = "Network error, please try again.";
}
});Event delegation on a list
One listener on the list handles every delete button, including rows added after the page loaded.
const list = document.querySelector("#todo-list");
list.addEventListener("click", (event) => {
const button = event.target.closest("button[data-action=delete]");
if (!button || !list.contains(button)) return;
button.closest("li").remove();
});A passive scroll listener throttled to one update per frame
passive: true lets scrolling start right away, and requestAnimationFrame keeps the work to once per frame.
const header = document.querySelector("header");
let queued = false;
window.addEventListener("scroll", () => {
if (queued) return;
queued = true;
requestAnimationFrame(() => {
header.classList.toggle("is-scrolled", window.scrollY > 40);
queued = false;
});
}, { passive: true });once and AbortController
The first listener runs a single time. The others are all removed together by one abort() call.
document.querySelector("#cookie-ok")
.addEventListener("click", () => banner.remove(), { once: true });
const controller = new AbortController();
const { signal } = controller;
window.addEventListener("resize", onResize, { signal });
document.addEventListener("keydown", onKey, { signal });
// when this feature is torn down:
controller.abort();Keyboard shortcut that ignores typing in fields
Checking the target stops the shortcut from firing while someone is typing a slash into a search box.
document.addEventListener("keydown", (event) => {
const typing = event.target.closest("input, textarea, select, [contenteditable]");
if (event.key === "/" && !typing) {
event.preventDefault();
document.querySelector("#search").focus();
}
});
How an event travels
A dispatched event moves in three phases. It travels down from the window to the target in the capture phase, reaches the target, then bubbles back up through each ancestor. Listeners run in the bubble phase unless you ask for capture.
stopPropagation halts the journey, so ancestors never hear it. Use it rarely, since delegated listeners and analytics further up the tree silently stop working.
Scroll without slowing the page
Scroll events can fire many times per frame of movement. Keep the handler tiny, read positions instead of writing layout, and batch visual updates inside requestAnimationFrame.
For jobs like revealing elements as they enter view, an IntersectionObserver is usually cheaper than measuring on every scroll. The scrollend event, Baseline since December 2025 according to MDN, fires once when movement stops.
Cleaning up listeners
Listeners on long-lived objects such as window or document keep their handler, and anything it references, alive. When the part of the page that needed them goes away, remove them.
The signal option makes this tidy. Create one AbortController per feature, pass its signal to every listener, and call abort() once during teardown.
How it works
- Use the controls in the test area: click the buttons, type in the field, submit the form and scroll the box.
- Each listener call appears in the log with its event type, the element that started it and the element that handled it.
- Turn on once to see a listener disappear after one call, or turn off delegation to see the list handle clicks per item instead.
- Copy any of the examples below. Every one is plain JavaScript with no library.
Tips
- Pass a named function when you plan to remove the listener. An inline arrow function cannot be matched later.
- AbortController removes a whole group of listeners with one abort() call, which suits components that mount and unmount.
- Listen for submit on the form, not click on the button, so pressing Enter in a field is handled too.
- Use event.target.closest("selector") in delegated handlers. A click on an icon inside a button still finds the button.
- focus and blur do not bubble. Delegate focusin and focusout instead.
Frequently asked questions
What is event delegation?
Instead of attaching a listener to every item, you attach one to a shared parent. Because most events bubble up, the parent hears clicks from all its children, including items added later, and uses event.target to tell which one was clicked.
Why does removeEventListener not remove my listener?
It must receive the same function reference and the same capture setting that addEventListener was given. Two arrow functions with identical code are still different functions, so define the handler once and pass that variable both times.
What does passive: true do?
It tells the browser your handler will not call preventDefault, so the page can start scrolling immediately rather than waiting for your code to finish. Browsers already default to passive for wheel and touch listeners on window, document and body.
What is the difference between target and currentTarget?
target is the innermost element where the event started, and it stays the same as the event bubbles. currentTarget is the element whose listener is running right now, which changes at each level.
Does form.submit() fire the submit event?
No. Calling form.submit() from a script skips the submit event and skips validation. Call form.requestSubmit() when you want your submit listeners and the built-in checks to run.
addEventListener or onclick?
The onclick property holds one function, so assigning a second one replaces the first. addEventListener lets several independent listeners share an element and supports the options object, so it is the better default.
Related: JavaScript accordion and tabs, JavaScript fetch and async, How to add a contact form, localStorage in JavaScript, Keyboard and screen reader testing.
Start a 7-day free trial or see all free tools. On We.Inc you get a 7-day free trial, not a free plan: card needed, $0 today, cancel before it ends and you pay nothing. AI building is on paid plans from $20 a month.
More in Guides
- localStorage in JavaScript (with Working Examples)
- The JavaScript For Loop, and Which Loop to Use
- JavaScript Objects, and Why You See [object Object]
- Reload the Page with JavaScript: location.reload()
- Scroll to an Element with JavaScript
- Sort an Array of Objects in JavaScript
- JavaScript String Methods Cheat Sheet (Live)
- JavaScript Websites and AI Crawlers: Can They See Your Pages? | How-to Guide
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App