Today I Learned - Rocky Kev

TIL how to remove a event listener

POSTED ON:

TAGS:

Maybe you have a situation where you only want the event to fire once.

To Remove the Event

const removeEventOffElement = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);

const testFunction = () => console.log('My function has been called');

document.body.addEventListener('click', testFunction);// Call remove method

removeEventOffElement(document.body, 'click', fn);

To turn off the event after it's fired

const myButton = document.getElementById("myBtn");

const myClickFunction = () => {
console.log('this click will only get called once')
}

myButton.addEventListener('click', myClickHandler, {
once: true,
});

REFERENCE:
21 Useful JavaScript Snippets For Everyday Development


Related TILs

Tagged:

TIL why you should always use textContent

Today I learned the difference between 'Node.textContent'. It handles all elements, even hidden ones. It also prevents XSS attacks since it strips tags.

TIL prepend

When you're creating new elements in Javascript, you want to attach the new element to something that exists in the DOM already. You do that with append, and prepend.

TIL the simulating a Pipe function

It’s a pipe function that allows you to chain multiple operations together by taking a series of functions as arguments and applying them in a specific order to the input.