Skip to main content

DOM Events

Events are actions or occurrences that happen in the browser, which you can respond to with JavaScript. Understanding events is crucial for creating interactive web applications.

Adding Event Listeners

In order to add an event listener to an element, you can use the EventTarget.addEventListener() method. Yet, in some cases, adding a listener for every single element can be a bit of a performance hit.

Basic Event Listener

Event Delegation

In these cases, you can use event delegation to add a single event listener to a parent element and then check if the event target matches the target you’re looking for.
Event delegation is more efficient when you have many elements with the same event listener, as it requires only one listener instead of many.

Removing Event Listeners

Removing an event listener from an element is as easy as adding one. You can use the EventTarget.removeEventListener() method to remove an event listener from an element.
You must pass the same function reference to removeEventListener that you passed to addEventListener. Arrow functions and anonymous functions won’t work for removal.

Common Events

Mouse Events

Keyboard Events

Form Events

Window Events

Triggering Custom Events

JavaScript’s EventTarget.dispatchEvent() method allows you to trigger an event programmatically. This method accepts an Event object as its only argument, which can be created using the CustomEvent constructor.

Basic Custom Event

The CustomEvent constructor allows you to pass custom data to the event listener through the detail property.

Custom Event with Options

Event Object Properties

Common Properties

Mouse Event Properties

Keyboard Event Properties

Event Methods

preventDefault()

Prevents the default action of the event:

stopPropagation()

Stops the event from bubbling up the DOM tree:

stopImmediatePropagation()

Stops event bubbling and prevents other listeners on the same element:

Event Options

Capture Phase

Once

Passive

Practical Examples

Debounced Scroll Handler

Click Outside to Close

Keyboard Shortcuts

Best Practices

When elements are added/removed dynamically, event delegation ensures events work without re-attaching listeners.
Always remove event listeners when elements are destroyed or components unmount to prevent memory leaks.
Mark scroll and touch event listeners as passive to improve performance, unless you need preventDefault().
Avoid onclick="..." in HTML. Use addEventListener in JavaScript for better separation of concerns.
For events that fire frequently (scroll, resize, mousemove), use throttling or debouncing to limit execution.