1

document.getElementById('divv').addEventListener("click",func)
  function func(a){
   alert("oooo");
  }
  function abc(){
   document.getElementById('divv').removeEventListener("click",function(){func()});
  }
<div id="divv">This is vivek</div>
 <button onclick="abc()">Remove</button>

I have a button and I want to remove the onclick event on a div after I click on the button.

sao
  • 1,835
  • 6
  • 21
  • 40
Rajesh purohit
  • 178
  • 1
  • 8
  • 2
    Yes, `removeEventListener` does not work like that. Attach a named function (either declared or assigned to a variable) as an event listener, and refer the same named function when removing the listener. – Teemu Oct 09 '19 at 11:15
  • Possible duplicate of [JavaScript: remove event listener](https://stackoverflow.com/questions/4402287/javascript-remove-event-listener) – zero298 Oct 09 '19 at 13:59

2 Answers2

1

Just like that:

document.getElementById('divv').removeEventListener("click", func);

See the explanation about removeEventListener

document.getElementById('divv').addEventListener("click", func)

function func(a) {
  alert("oooo");
}

function abc() {
  document.getElementById('divv').removeEventListener("click", func);
}
<div id="divv">This is vivek</div>
<button onclick="abc()">Remove</button>
tom
  • 9,550
  • 6
  • 30
  • 49
0

You are not adding and removing the same function, and that is why it doesn't work.

You are adding like this: .addEventListener("click", func")

And you are removing like this: .removeEventListener("click", function(){func()})

func and function(){func()} do not refer to the same function, even though they have the same result, when called.

You need to remove exactly the same way as you remove; otherwise removing won't "find" the original function you added:

function abc(){
    document.getElementById('divv').removeEventListener("click",func);
}
Anders Marzi Tornblad
  • 18,896
  • 9
  • 51
  • 66