Event Handling in JavaScript: A Practical Guide with Examples
Get a summary of this article:

The short answer
Event handling in JavaScript means listening for things that happen in the browser, like clicks, key presses and form submits, and running a function when they do. The standard way is one line:
button.addEventListener('click', handleClick);
That function is your event handler. Everything else in this guide (the event object, bubbling, delegation, cleanup and how frameworks do it) builds on that one idea.
TL;DR
- Events are things that happen in the browser: a click, a key press, a form submit, the page loading.
- Attach handlers with addEventListener(). It supports several handlers per event and clean removal.
- The event object tells you what happened: target, type, key, plus preventDefault() and stopPropagation().
- Events bubble up from an element through its parents, which is what makes event delegation work.
- Clean up listeners you no longer need to avoid memory leaks. React, Angular, Vue and Ext JS handle most of this for you.
What are events in JavaScript?
Events are signals that something just happened in the browser: someone clicked a button, typed in a field, submitted a form or scrolled, or the page finished loading. Your code listens for those signals and responds, and that’s what makes a page interactive.
These are the events you’ll use most:
| Event | When it fires | Common use |
|---|---|---|
| click | An element is clicked or tapped | Buttons, links, menus |
| input | A field’s value changes as the user types | Live search, inline validation |
| change | A field’s value is committed (e.g. a select or checkbox) | Dropdowns, toggles |
| submit | A form is submitted | Validating and sending forms |
| keydown / keyup | A key is pressed or released | Shortcuts, Enter and Escape handling |
| pointerdown / pointerup | A mouse, pen or finger presses or lifts | Drag and drop, drawing, custom controls |
| mouseover / mouseout | The pointer enters or leaves an element | Hover effects, tooltips |
| focus / blur | An element gains or loses focus | Form hints, accessibility |
| scroll / resize | The page scrolls or the window resizes | Lazy loading, responsive layouts |
| DOMContentLoaded / load | The HTML, or all resources, have loaded | Starting your app code |
Tip: pointer events (pointerdown, pointermove, pointerup) cover mouse, touch and pen with one set of handlers, so prefer them over separate mouse and touch events for new code.
What is event handling?
Event handling is the code that responds to events. The function that runs is called an event handler (or event listener). There are three ways to attach one:
| Method | Example | Verdict |
|---|---|---|
| addEventListener() | button.addEventListener(‘click’, save) | Use this. Several handlers per event, options like once and passive, clean removal |
| DOM property | button.onclick = save | Fine for quick scripts, but only one handler per event; a second assignment silently replaces the first |
| HTML attribute | <button onclick=”save()”> | Avoid. It mixes code into markup and is blocked by strict Content Security Policies |
Here’s the recommended way in action:
const button = document.querySelector('#save');
button.addEventListener('click', (event) => {
console.log('Saved!', event.type); // 'click'
});
The event object
Every handler receives an event object that describes what happened. These are the properties and methods you’ll reach for most:
| Property or method | What it gives you |
|---|---|
| event.target | The element where the event started (e.g. the exact button clicked) |
| event.currentTarget | The element the listener is attached to |
| event.type | The event name, such as ‘click’ |
| event.key | Which key was pressed (keyboard events) |
| event.preventDefault() | Stops the browser’s default action, like a form submitting or a link navigating |
| event.stopPropagation() | Stops the event travelling further up (or down) the page |
The classic use of preventDefault() is keeping a form on the page so you can validate and send it yourself:
form.addEventListener('submit', (event) => {
event.preventDefault(); // don't reload the page
const data = new FormData(form);
// validate, then send with fetch()
});
Event bubbling and capturing
When you click a button, the event doesn’t just happen on the button. It travels through the page in three phases:
- Capturing: the event travels from window down through each parent to the element.
- Target: it reaches the element itself, and that element’s listeners run.
- Bubbling: it travels back up through each parent to window.
By default, listeners run during bubbling. That’s why a click on a button inside a card also reaches the card’s listener, and the page’s. To listen during capturing instead, pass { capture: true }:
card.addEventListener('click', onCardClick, { capture: true }); // runs before the button's handler
If you need the event to stop where it is, call event.stopPropagation(). Use it sparingly, though: other code (analytics, a dropdown that closes on outside clicks) may rely on the event reaching the top.
Event delegation
Because events bubble, you don’t need a listener on every child element. Put one listener on the parent and check where the event came from. This is event delegation, and it has two big advantages: fewer listeners to create and clean up, and it automatically works for children added later.
// Without delegation: one listener per item, and new items get none
document.querySelectorAll('.item').forEach((item) => {
item.addEventListener('click', handleClick);
});
// With delegation: one listener handles every item, now and later
list.addEventListener('click', (event) => {
const item = event.target.closest('.item');
if (item && list.contains(item)) {
handleClick(item);
}
});
Note the closest() call. If an item contains an icon or a <span>, event.target is that inner element, not the item. closest(‘.item’) walks up to the item itself, which is a common bug in delegation code that only checks event.target.matches().
Removing event listeners (and avoiding memory leaks)
Listeners you forget to remove keep their functions, and everything those functions reference, in memory. In single-page apps where views come and go all day, that adds up. You have three ways to clean up:
// 1. removeEventListener: pass the SAME function you added
window.addEventListener('resize', onResize);
window.removeEventListener('resize', onResize);
// 2. once: the listener removes itself after the first call
dialog.addEventListener('close', onClose, { once: true });
// 3. AbortController: remove several listeners in one go
const controller = new AbortController();
window.addEventListener('resize', onResize, { signal: controller.signal });
window.addEventListener('scroll', onScroll, { signal: controller.signal });
controller.abort(); // both listeners removed
Frameworks give you a place to do this automatically: React’s useEffect cleanup function, Angular’s DestroyRef / ngOnDestroy, Vue’s onUnmounted, and ReExt component lifecycle, which removes a component’s listeners when it’s destroyed.
Common event-handling mistakes
Calling the handler instead of passing it. button.addEventListener(‘click’, save()) runs save immediately and registers its return value. Pass the function itself: addEventListener(‘click’, save).
Trying to remove an anonymous function. This never works, because the two arrow functions are different objects:
el.addEventListener('click', () => doThing());
el.removeEventListener('click', () => doThing()); // removes nothing
Keep a reference to the function, or use an AbortController.
Losing this. In a regular function handler, this is the element. In an arrow function, it’s whatever this was outside. Use event.currentTarget to get the element reliably either way.
Adding the same listener over and over. The browser ignores a second addEventListener with the same function, but an inline arrow is a new function every time. Attach one inside code that runs on every render or update and the duplicates stack up. Attach once, or clean up before re-attaching.
Forgetting keyboard users. A <div> with a click handler can’t be reached or activated with the keyboard. Use a real <button>, which handles Enter, Space and focus for free.
Debouncing and throttling high-frequency events
Events like scroll, resize, input and pointermove can fire dozens of times a second. Running heavy code on every one makes the page janky. Two patterns fix it:
- Debounce: wait until the events stop for a set time, then run once. Perfect for search-as-you-type or saving a draft.
- Throttle: run at most once per interval while the events keep coming. Good for scroll-position tracking or infinite scroll.
// Debounce: run after the user pauses for `delay` ms
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
searchInput.addEventListener('input', debounce((e) => search(e.target.value), 300));
// Throttle: run at most once every `delay` ms
function throttle(fn, delay) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= delay) {
last = now;
fn.apply(this, args);
}
};
}
window.addEventListener('scroll', throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 100), { passive: true });
For visual updates tied to scrolling or pointer movement, requestAnimationFrame is often an even better throttle, because it lines your work up with the browser’s next repaint.
Passive listeners
Notice { passive: true } above. It promises the browser that your handler won’t call preventDefault(), so it can scroll immediately instead of waiting for your code. Use it on scroll, wheel and touch listeners whenever you don’t need to block the default behaviour.
Custom events
You’re not limited to the browser’s built-in events. CustomEvent lets parts of your app talk to each other without being tightly coupled:
// Announce something happened, with data attached
cart.dispatchEvent(new CustomEvent('cart:updated', {
detail: { itemCount: 3 },
bubbles: true,
}));
// Listen for it anywhere up the tree
document.addEventListener('cart:updated', (event) => {
badge.textContent = event.detail.itemCount;
});
Set bubbles: true if you want parents to hear it, and put your data in detail. Prefixing names (cart:updated) avoids clashes with built-in or third-party events.
Accessible event handling
Interactive elements must work for keyboard and screen-reader users too:
- Use native controls. <button>, <a href> and form inputs handle focus, Enter and Space for free.
- Prefer click on buttons over mousedown or pointerdown; it fires for keyboard activation as well.
- Make custom widgets reachable with tabindex=”0″, a suitable role, and keydown handling for the keys users expect (arrows in a menu, Escape to close).
- Don’t rely on hover alone. Anything shown on mouseover should also appear on focus.
Event handling in JavaScript frameworks
Everything above still applies inside a framework; frameworks just wrap it in their own syntax, handle most cleanup for you, and add patterns for passing events between components. Here’s how the four main options compare in practice.
React: SyntheticEvents and automatic delegation
React wraps native events in SyntheticEvents, which behave consistently across browsers and have the same interface you already know (target, preventDefault() and so on). Under the hood, React attaches one listener per event type at your app’s root and dispatches to your handlers, so delegation happens automatically.
import { useState, useEffect } from 'react';
function ProductList({ items }) {
const [selectedId, setSelectedId] = useState(null);
// Global listener: add it in an effect and remove it in the cleanup
useEffect(() => {
const onKeyDown = (e) => {
if (e.key === 'Escape') setSelectedId(null);
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, []);
return (
<ul className="product-list">
{items.map((item) => (
<li key={item.id}>
<button
type="button"
aria-pressed={selectedId === item.id}
onClick={() => setSelectedId(item.id)}
>
{item.name}
</button>
</li>
))}
</ul>
);
}
A few things worth knowing:
- Handlers in JSX clean up automatically when the component unmounts. Listeners you add yourself, like the window one above, need a useEffect cleanup.
- Event objects are no longer pooled (since React 17), so you can use them in async code.
- Real buttons give you keyboard support for free; React won’t add it to a clickable div.
- Custom events between components are usually just callback props (onSelect) or context.
Building a full React app? See our guide to the best React frameworks.
Angular 22: event binding with signals
Angular binds events in the template with parentheses, (click)=”…”, and calls methods on your component. With signals, a handler updates state and Angular re-renders just what depends on it; in Angular 22, new apps are zoneless by default.
import { Component, signal, computed, output } from '@angular/core';
interface Task { id: number; title: string; status: string; }
@Component({
selector: 'app-task-list',
host: { '(document:keydown.escape)': 'clear()' }, // global listener, removed automatically
template: `
<ul class="task-list">
@for (task of tasks(); track task.id) {
<li>
<button type="button"
[class.selected]="selectedId() === task.id"
(click)="select(task)">
{{ task.title }} – {{ task.status }}
</button>
</li>
}
</ul>
<p>Selected: {{ selectedTitle() }}</p>
`,
})
export class TaskListComponent {
tasks = signal<Task[]>([
{ id: 1, title: 'Review code', status: 'pending' },
{ id: 2, title: 'Deploy app', status: 'completed' },
]);
selectedId = signal<number | null>(null);
selectedTitle = computed(() =>
this.tasks().find((t) => t.id === this.selectedId())?.title ?? 'None selected');
taskSelected = output<Task>(); // custom event for the parent component
select(task: Task) {
this.selectedId.set(task.id);
this.taskSelected.emit(task);
}
clear() {
this.selectedId.set(null);
}
}
- Key modifiers such as (keydown.enter) and (keydown.escape) filter keyboard events in the template. Angular has no .stop or .prevent modifiers; call event.stopPropagation() or event.preventDefault() in your method.
- Angular attaches listeners directly to each element rather than delegating, and removes them when the component is destroyed.
- Global listeners go in the host property (as above) so Angular cleans them up for you.
- Custom events between components use output(); app-wide events usually go through a shared service.
Vue 3.5: concise syntax with built-in modifiers
Vue’s @event syntax is probably the most concise of the four, and its event modifiers handle common chores right in the template: .prevent, .stop, .once, and key modifiers like .enter and .esc.
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
interface Product { id: number; name: string; price: number; }
const products = ref<Product[]>([
{ id: 1, name: 'Laptop', price: 999 },
{ id: 2, name: 'Mouse', price: 29 },
]);
const selectedId = ref<number | null>(null);
const searchTerm = ref('');
const filtered = computed(() =>
products.value.filter((p) =>
p.name.toLowerCase().includes(searchTerm.value.toLowerCase())));
const emit = defineEmits<{ select: [product: Product] }>(); // custom event
function selectProduct(product: Product) {
selectedId.value = product.id;
emit('select', product);
}
// Global listener with cleanup
const onKeydown = (e: KeyboardEvent) => {
if (e.key === 'Escape') selectedId.value = null;
};
onMounted(() => document.addEventListener('keydown', onKeydown));
onUnmounted(() => document.removeEventListener('keydown', onKeydown));
</script>
<template>
<input v-model="searchTerm" type="search" placeholder="Search products…" />
<ul class="product-grid">
<li v-for="product in filtered" :key="product.id">
<button
type="button"
:class="{ selected: selectedId === product.id }"
@click="selectProduct(product)"
>
{{ product.name }} – ${{ product.price }}
</button>
</li>
</ul>
</template>
- Handlers update reactive state directly, and Vue’s Proxy-based reactivity (in place since Vue 3.0) re-renders only what changed.
- Template listeners clean up automatically; global ones need onUnmounted, or the useEventListener helper from VueUse, which does both steps for you.
- Custom events go up to the parent with defineEmits. Vue 3 removed the old global event bus, so teams use a small library such as mitt, or shared state, for app-wide events.
Ext JS 8.0: an event system built for data-heavy apps
We built Ext JS for enterprise apps where a single screen might show tens of thousands of grid rows. Its event system leans on the same principles covered above, applied for you: grids use delegation (one listener on the container rather than one per cell), listeners can be buffered to tame high-frequency events, and a component’s listeners are removed automatically when it’s destroyed.
Ext.define('MyApp.view.ProductGrid', {
extend: 'Ext.grid.Panel',
xtype: 'productgrid',
store: {
fields: ['id', 'name', 'category', 'price', 'inStock'],
data: [
{ id: 1, name: 'Enterprise Laptop', category: 'Hardware', price: 1299, inStock: true },
{ id: 2, name: 'Wireless Mouse', category: 'Accessories', price: 59, inStock: false }
]
},
columns: [
{ text: 'ID', dataIndex: 'id', width: 50 },
{ text: 'Product Name', dataIndex: 'name', flex: 1 },
{ text: 'Category', dataIndex: 'category', width: 120 },
{ text: 'Price', dataIndex: 'price', width: 100,
renderer: (value) => Ext.util.Format.currency(value) },
{ text: 'In Stock', dataIndex: 'inStock', width: 80,
renderer: (value) => (value ? 'Yes' : 'No') }
],
listeners: {
// Grid-level event
selectionchange: function (selModel, selected) {
this.fireEvent('productselected', selected); // custom event for other components
},
// Cell clicks are delegated: one listener serves every cell
cellclick: function (view, td, cellIndex, record) {
const column = view.getGridColumns()[cellIndex];
if (column && column.dataIndex === 'inStock') { // safer than a fixed column number
this.toggleStock(record);
}
},
// Buffered: waits 300 ms and runs once, even if the event repeats
itemdblclick: {
fn: function (view, record) { this.editProduct(record); },
buffer: 300
}
},
initComponent: function () {
this.callParent();
// Keyboard shortcuts on the grid
this.on('afterrender', function () {
this.keyMap = new Ext.util.KeyMap({
target: this.getEl(),
binding: [
{ key: Ext.event.Event.DELETE, fn: this.deleteSelected, scope: this },
{ key: 'n', ctrl: true, fn: this.addNewProduct, scope: this }
]
});
}, this);
// A KeyMap you create yourself is yours to destroy
this.on('destroy', function () {
Ext.destroy(this.keyMap);
}, this);
},
toggleStock: function (record) {
record.set('inStock', !record.get('inStock'));
record.commit();
this.fireEvent('stockchanged', record);
},
editProduct: function (record) {
Ext.create('Ext.window.Window', {
title: 'Edit Product: ' + record.get('name'),
modal: true, width: 400, height: 300, layout: 'fit',
items: [{
xtype: 'form', bodyPadding: 10,
items: [
{ xtype: 'textfield', fieldLabel: 'Product Name', name: 'name', value: record.get('name') },
{ xtype: 'numberfield', fieldLabel: 'Price', name: 'price', value: record.get('price') }
],
buttons: [{
text: 'Save',
handler: function () {
const form = this.up('form').getForm();
if (form.isValid()) {
record.set(form.getValues());
this.up('window').close();
}
}
}]
}]
}).show();
},
deleteSelected: function () {
const selection = this.getSelection();
if (selection.length) this.getStore().remove(selection);
},
addNewProduct: function () {
const [record] = this.getStore().add({ name: 'New Product', category: 'Uncategorized', price: 0, inStock: true });
this.getSelectionModel().select(record);
}
});
The pattern to notice: listeners declared in the component config are cleaned up with the component, but anything you create yourself, like the KeyMap here, you destroy yourself. Custom events fired with fireEvent let other components react to changes without direct references, which keeps large apps loosely coupled.
Framework event handling compared
| React 19 | Angular 22 | Vue 3.5 | Ext JS 8.0 | |
|---|---|---|---|---|
| Event model | SyntheticEvents wrapping native events | Native events, template binding | Native events, template binding | Framework event system on components and data |
| Delegation | Automatic, at the app root | Direct listeners per element | Direct listeners per element | Automatic in grids and views |
| Cleanup | Automatic for JSX handlers; useEffect for your own | Automatic for template and host listeners | Automatic for template listeners; onUnmounted for your own | Automatic for config listeners; destroy what you create |
| Template shortcuts | None (plain JS in handlers) | Key modifiers (keydown.enter) | Event and key modifiers (.prevent, .stop, .enter) | Listener options (buffer, delay, single) |
| Custom events | Callback props, context | output(), services | defineEmits, mitt or shared state | fireEvent on any component |
| Learning curve | Medium | Steeper | Gentle | Medium to steep |
Raw event speed rarely decides between these; all four are fast enough for typical interfaces. What differs is how much you build yourself once the data gets big: virtualised grids, buffering and cleanup patterns come built in with some options and are your job with others.
How to choose a framework for event-heavy apps
There’s no single best JavaScript framework for event handling, but four questions narrow it down quickly:
- How complex is the interface? React or Vue serve consumer apps with straightforward interactions. Data-dense enterprise screens (big grids, many linked forms) benefit from a framework that ships those components with events already wired, such as Ext JS. Angular sits comfortably in between with strong structure for larger teams.
- How much data is on screen? Once a view holds thousands of rows or elements, you need virtualisation and delegation. Ext JS provides them out of the box; with React and Vue, you’ll add a grid library and tune it.
- What does your team already know? React has the largest talent pool, Angular’s conventions help large teams stay consistent, and Vue is the easiest to pick up.
- What does a prototype say? Build the most event-heavy screen in your top candidates, load it with realistic data, and measure responsiveness and memory over a long session.
Frequently asked questions
What is event handling in JavaScript?
Running code in response to events such as clicks, key presses, or form submits. You attach a function (an event handler) to an element, usually with addEventListener(), and the browser calls it when the event happens.
What are JavaScript events?
Signals the browser sends when something happens: a user clicks, types, scroll,s or submits a form, or the page finishes loading. Common examples are click, input, change, submit, keydo,wn and load.
What’s the difference between an event handler and an event listener?
In everyday use, nothing: both mean a function that runs when an event fires. Strictly, addEventListener() registers a listener, while handler often refers to the onclick-style property. Prefer addEventListener(), because it supports several handlers per event.
What is event bubbling?
When an event fires on an element, it then travels up through each of its parents. That’s what makes event delegation possible. You can stop it with event.stopPropagation().
What’s the difference between bubbling and capturing?
Capturing is the first phase, when the event travels down from window to the target. Bubbling is the last phase, when it travels back up. Listeners run during bubbling by default; pass { capture: true } to run during capturing.
What does preventDefault() do?
It stops the browser’s default action for an event, such as a form reloading the page on submit or a link navigating away.
What’s the difference between stopPropagation() and preventDefault()?
preventDefault() cancels the browser’s built-in action but lets the event keep travelling. stopPropagation() stops the event travelling to other elements but doesn’t cancel the default action. They solve different problems and can be used together.
How do you remove an event listener?
Call removeEventListener() with the same event type and the same function reference you added. You can also use { once: true } for one-time listeners, or an AbortController to remove several at once.
What is the difference between debounce and throttle?
Debounce waits until events stop for a set time, then runs once (search-as-you-type). Throttle runs at most once per interval while events keep firing (scroll tracking).
How do I create a custom event?
Create one with new CustomEvent(‘name’, { detail: data, bubbles: true }), fire it with element.dispatchEvent(event), and listen for it with addEventListener(‘name’, …) like any other event.
How does event delegation work in frameworks?
React and Ext JS (in grids and views) delegate automatically. Angular and Vue attach listeners directly to elements, so you implement delegation yourself when a list gets large.
What’s the difference between native DOM events and framework event systems?
Framework event systems sit on top of native events. React’s SyntheticEvents normalise browser differences; Angular and Vue add template syntax and modifiers; Ext JS adds buffering, delegation in data views and automatic cleanup tied to components.
How do you prevent memory leaks in framework event handlers?
Use each framework’s cleanup point: React’s useEffect cleanup, Angular’s host listeners or DestroyRef, Vue’s onUnmounted, or Ext JS’s component lifecycle. And always remove global listeners (on window or document) that you added yourself.
Which framework is best for data-intensive apps with heavy event handling?
Ext JS 8.0 is designed for data-intensive enterprise apps, with delegation, buffering and virtualised grids built in. React and Vue can reach similar results with a grid library and careful tuning.
Conclusion
Event handling in JavaScript comes down to a handful of ideas: listen with addEventListener(), read the event object, understand bubbling, delegate when you have many similar elements, tame high-frequency events with debounce or throttle, and clean up listeners you no longer need.
Frameworks build on those same foundations. React adds SyntheticEvents and automatic delegation, Angular ties events to signals and templates, Vue offers the most concise syntax with handy modifiers, and Ext JS adds delegation, buffering and lifecycle cleanup tuned for big data screens.
Building financial dashboards, ERP systems or large-scale data tools? Start your free Ext JS 8.0 evaluation and see how its event system handles your data.
Every enterprise React team eventually asks the question: should we build our own UI component…
The short answer: No. React is a JavaScript library for building user interfaces. It renders…
There’s no shortage of React component libraries. There is a shortage of honest guidance on…




