Checkout the code...
document.querySelectorAll("button").forEach((element) => {
element.addEventListener("keypress", respondToClick);
function respondToClick() {
console.log("Key Pressed");
console.log(element);
}
});
/*
'I don't know where to put...'
// RemoveEventListener
const removeEvent = () => {
element.removeEventListener("click", respondToClick);
};
*/
// On HTML file
<button onclick="removeEvent();" class="numbers">RemoveEventListener</button>;
Can I add removeEventListner button that will remove an eventListner inside an element?
You can do it this way without inline JS (more info on why to not do it)
here's more info on removeEventListener on MDN
function respondToClick(event) {
const element = event.target;
console.log("Key Pressed:", event.key);
console.log(element);
}
function removeEvent(event) {
const element = event.target;
element.removeEventListener("keypress", respondToClick)
}
document.querySelectorAll("button").forEach((element) => {
element.addEventListener('keypress', respondToClick);
element.onclick = removeEvent;
});
<button>removeEventListener</button>