DEV Community

Morris John
Morris John

Posted on

removeEventListener not working.

I don't seem to understand why I can't remove the event listener where I added a text through insertAdjacentText when clicked. I really hope someone helps me. I've gone through hours trying to debug it.

const header = document.querySelector(`header h1`);
const button = document.querySelector(`header button`);

function addText() {
   header.insertAdjacentText(`afterend`, `Yeah`);
   console.log(`yeah`);
}

header.addEventListener(`click`, addText);
button.removeEventListener(`click`, addText);

Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
merri profile image
Vesa Piittinen

My guess of what you want is this:

const header = document.querySelector(`header h1`);
const button = document.querySelector(`header button`);

function addText() {
   header.insertAdjacentText(`afterend`, `Yeah`);
   console.log(`yeah`);
   button.removeEventListener(`click`, addText);
}

button.addEventListener(`click`, addText);
Enter fullscreen mode Exit fullscreen mode

Add listener to button, upon clicking remove the listener from the button.

Collapse
 
dbarwikowski profile image
Daniel Barwikowski

You've added listener to the header but you remove it from button.
Why it should work?

Collapse
 
leastbad profile image
leastbad

The element, event and callback together work like a signature.

You must remove the handler from the same element that you put it on or else the signature will be different.

Collapse
 
finnanton profile image
Finn

I guess this is a common Javascript Problem.
javascript.info/bubbling-and-captu...

But please correct me when I'm wrong.