Event Listener Utils

Utility library for adding backwards compatible event listeners

A tiny utilities library for dealing with event listeners.

Exposes addListener, removeListener functions.

This library will work with analytics or as a standalone package.

See live demo.

Why this package?

This package makes it a little easy to work with addEventListener & removeEventListener by returning a clean up function for both. This makes it easy to re-attach a listener or disable a listener with it's return function.

Additionally this package is backwards compatible with older browsers. This library is backwards compatible back to IE 8.

How to install

Install @analytics/listener-utils from npm.

npm install @analytics/listener-utils


Below is the api for @analytics/listener-utils.


Add an event listener to an element.

import { addListener } from '@analytics/listener-utils'

const button = document.querySelector('#my-button')
const options = {} // (optional) See opts at

// addListener returns a disable listener function
const disableListener = addListener(button, 'click', () => {
  console.log('wow you clicked it!')
}, options)

// Detach the listener

Below is an example of automatically disabling a click handler while an api request is in flight

import { addListener } from '@analytics/listener-utils'

const apiButton = document.querySelector('#api')
const disableFetchListener = addListener(apiButton, 'click', () => {
  // Fetch in progress disable click handler to avoid duplicate calls
  const renableAPIClickHandler = disableFetchListener()

    .then((response) => {
      return response.json()
    .then((json) => {
      console.log("data", json.results)
      // Success! Reattach event handler
    .catch((err) => {
      console.log('API error', err)
        // Error! Reattach event handler

// call disableFetchListener wherever you wish to disable this click handler

See addEventListener docs for options


Removes an event listener from an element.

import { addListener, removeListener } from '@analytics/listener-utils'

const button = document.querySelector('#my-button')
const simpleFunction = () => console.log('wow you clicked it!')
addListener(button, 'click', simpleFunction)

const options = {} // (optional) See opts at

// removeListener returns an enable listener function
const reAttachListener = removeListener(button, 'click', simpleFunction, options)

// Reattach the listener

See removeEventListener docs for options