← All resources
The toolkit · Resource guide

Clean up a temporary event listener

Remove related event listeners through an AbortController when a component closes.

Visit website (opens in a new tab)
Understand the tool

Overview

Remove related event listeners through an AbortController when a component closes.

The example below is an original, minimal illustration of the referenced web-platform feature. Read the official reference and adapt it before using it in a real project.

Best for

  • Understanding clean up a temporary event listener.
  • Trying the pattern in an isolated page.
  • Adapting the example to an existing website.

Key features

  • Abortable listeners
  • Component cleanup
  • Event lifecycle
A practical walkthrough

Getting started

  1. Read the example and reference. Identify the selectors, files or values that belong to your project.

  2. Try it in isolation. Use a disposable test page and adapt the example values.

  3. Verify before reuse. Check keyboard behavior, responsive layout and relevant browser support.

Things to know

  • These examples are learning material, not a drop-in application.
  • Replace example filenames, selectors and routes as needed.
  • Test changes on staging and escape data for the context where it is used.

Code example

Original illustrative example. Adapt filenames and selectors, and test on staging before reuse.

const lifecycle = new AbortController();
window.addEventListener('resize', () => console.log('Layout changed'), { signal: lifecycle.signal });
// When the owning component is destroyed:
lifecycle.abort();

Useful alongside this

Accessibility

Text

Visual

Orientation

Accessibility settings