/

Useful JavaScript functions & snippets

javascript
On this page
  • Automatically remove an event listener after it has executed
  • The magical handleEvent function

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` 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

Edit this page
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Notes on code. My second brain, by Zander Martineau.