Useful JavaScript functions & snippets
On this page
Automatically remove an event listener after it has executed
js
el.addEventListener('click', console.log, {once: true,})
The magical handleEvent
function
js
// Get a reference to the <button>const btn = document.querySelector('button')// Define object with `handleEvent` functionconst myObject = {handleEvent: (event) => {alert(event.type)},}// Listen for 'click' events on the <button> and handle them with `myObject`... WHAT?!?!btn.addEventListener('click', myObject)
Remove query param
ts
// https://stackoverflow.com/a/58128921/91359export 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.hashhistory.replaceState(null, document.title, newUrl)}}