How can I remove a click event from an element in Javascript?

Viewed 37490

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?

2 Answers

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.

Related