Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 863
Stewart Alan Avatar asked Jul 16 '11 14:07

Stewart Alan


1 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.

like image 196
Koushik Das Avatar answered Sep 22 '22 19:09

Koushik Das