How can I remove an event listener in JavaScript?
You have to pass the same function to removeEventListener
that you passed to addEventListener
. The function you are passing to addEventListener
is
(e) => {
switch(e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
}
Since you are not storing a reference to it anywhere you cannot remove it. Assign that function to variable and use that to add and remove it:
const start = document.querySelector(".start")
const stopbtn = document.querySelector(".stop")
function handleKey(e) {
switch (e.keyCode) {
case 37: //left arrow key
console.log("left")
break
case 39:
console.log("right")
break
}
}
function keyboardControl() {
document.addEventListener("keydown", handleKey);
}
start.addEventListener("click", () => keyboardControl())
stopbtn.addEventListener(
"click",
() => document.removeEventListener("keydown", handleKey)
)
<button class="start">start</button>
<button class="stop">stop</button>
How to remove an event listener from window?
You need a reference to the function in order to remove it. Don't use anonymous functions, instead:
function handleKeyPress(event){
console.log(event)
if (event.key === ' ') {
startGame()
window.removeEventListener('keypress', (event))
}
})
//add it
window.addEventListener('keypress',handleKeyPress);
//remove it
window.removeEventListener('keypress',handleKeyPress);
.removeEventListener(); by name or reference?
You must pass a reference to the same function used for addEventListener
when calling removeEventListener
Javascript - Remove event listener at resize
Ok, so here it is the answer :
I had to split my function and do the condition in each.
window.addEventListener("DOMContentLoaded", onLoadFunction);
function onLoadFunction(e) {
onResizeFunction(); //trigger resize function immediately
window.addEventListener("resize", onResizeFunction);
}
function onResizeFunction(e) {
menu_onFocusDetection();
}
function initEntries() {
focusDetectionEntry = document.querySelectorAll('.nav-list--focus-detection > li[aria-expanded] > button');
}
function focus(e) {
this.parentElement.setAttribute('aria-expanded', 'true');
e.stopImmediatePropagation();
}
function menu_onFocusDetection() {
focusDetectionEntry.forEach(sub => {
var subParent = sub.parentElement;
if (window.innerWidth > 770) {
sub.addEventListener('focus', focus);
subParent.addEventListener('focusout', focusOut);
} else {
sub.removeEventListener('focus', focus);
subParent.removeEventListener('focusout', focusOut);
}
});
}
Remove event listener inside promise
Your problem is that you're not using what is returned from .addEventListener
. According to the docs, you need to use the returned SubscriptionObject
to remove the subscription. Try the following
const playSound = async (url) => {
try {
const promise = new Promise((resolve, reject) => {
const sound = SoundPlayer.addEventListener(
"FinishedPlaying",
({ success }) => resolve(sound)
);
});
SoundPlayer.playSoundFile(url, "mp3");
const sound = await promise;
SoundPlayer.stop();
sound.remove();
} catch (e) {
console.log(`cannot play the sound file`, e);
}
};
how to remove an eventlistener when it's directly added on HTML file
You can get the element and set the onclick attribute to null.
function addWatchlist() {
console.log('addWatchlist');
}
function removeListener() {
const button = document.getElementsByClassName('watch-list-btn')[0];
button.setAttribute('onclick', null);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/marx/4.0.0/marx.min.css" rel="stylesheet"/>
<button class="watch-list-btn" onclick="addWatchlist()">Watchlist</button>
<button onclick="removeListener()">Remove Listener</button>
Related Topics
Crockford'S Prototypal Inheritance - Issues With Nested Objects
Converting an Object to a String
Force Browser to Refresh CSS, JavaScript, etc
Webkit and Jquery Draggable Jumping
Using Jquery to Know When @Font-Face Fonts Are Loaded
Opera Preventdefault() on Keydown Event
How to Detect My Browser Version and Operating System Using JavaScript
Uncaught Referenceerror: Function Is Not Defined with Onclick
Calling a Parent Window Function from an Iframe
JavaScript Call() & Apply() VS Bind()
Sending Command Line Arguments to Npm Script
Jquery Drag/Resize with CSS Transform Scale
How to Make Jquery to Not Round Value Returned by .Width()
Access CSS File Contents via JavaScript