Reputation: 1643
I have a <div>
element that has a click event attached to it using the following code:
var id = "someId";
var elem = document.getElementById("elemId");
elem.addEventListener("click", function() { someFunction(id); }, false);
At a later point I copy the element and add it to another part of the DOM
, but need to first remove the click
event
var elem = document.getElementById("elemId");
elem.removeEventListener("click", ???? , false);
I'm not sure how to reference the listener and so far nothing I have tried has removed the event from the element.
Any ideas?
Upvotes: 16
Views: 56155
Reputation: 10813
The answer above is correct.
However, in case, someone is looking to remove the onclick
function which is attached to a button like this for eg
<button type="button" onclick="submit()" id="tour-edit-save">Save</button>
In this case, to remove the onclick
attached function, one will have to remove the attribute onclick
and that would work perfectly fine.
Here is how you would remove using pure JavaScript
document.getElementById('tour-edit-save').removeAttribute('onclick');
Using jquery
$('#tour-edit-save').removeAttr('onclick');
Hope this helps someone who's looking for this answer.
Upvotes: 8
Reputation: 123016
Move the anonymous click handler function out of the addEventListener
call:
var id = "someId";
var elem = document.getElementById("elemId");
var elemEventHandler = function() { someFunction(id); };
elem.addEventListener("click", elemEventHandler , false);
after which you should be able to:
var elem = document.getElementById("elemId");
elem.removeEventListener("click", elemEventHandler , false);
Upvotes: 11