Useful JavaScript functions & snippets

👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page

Automatically remove an event listener after it has executed Jump to heading

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

The magical handleEvent function Jump to heading

// 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 Jump to heading

// 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)
}
}

← Back home