Useful JavaScript functions & snippets

Automatically remove an event listener after it has executed

el.addEventListener('click', console.log, {
  once: true,
})

The magical handleEvent function

// Get a reference to the <button>
const btn = document.querySelector('button')

// Define object with `handleEvent` function
const myObject = {
  handleEvent: (event) => {
    alert(event.type)
  },
}

// Listen for 'click' events on the <button> and handle them with `myObject`... WHAT?!?!
btn.addEventListener('click', myObject)

More info

Remove query param

// https://stackoverflow.com/a/58128921/91359

export const removeSearchParam = (paramName: string): void => {
  const searchParams = new URLSearchParams(window.location.search)
  searchParams.delete(paramName)
  if (history.replaceState) {
    const searchString =
      searchParams.toString().length > 0 ? '?' + searchParams.toString() : ''
    const newUrl =
      window.location.protocol +
      '//' +
      window.location.host +
      window.location.pathname +
      searchString +
      window.location.hash
    history.replaceState(null, document.title, newUrl)
  }
}