Is there a way to remove event listener if I know only element and event, but don't know a function?
Something like:
var foo = getElementById("foo");
foo.removeEventListener('click');
Is there a way to remove event listener if I know only element and event, but don't know a function?
Something like:
var foo = getElementById("foo");
foo.removeEventListener('click');
There is no way to detach an event listener without having a reference to its listener method.
Method definition requires listener
to be specified.
It is possible to use some sort of custom functions like this:
function addEventListenerAndRemember(element, type, listener, useCapture)
{
if (!element.myEvents) element.myEvents = {};
if (!element.myEvents[type]) element.myEvents[type] = [];
element.myEvents[type].push(listener);
element.addEventListener(type, listener, useCapture || false);
}
function removeAllEventListener(element, type)
{
element.myEvents.forEach(function() {
element.myEvents[type].forEach(function(listener) {
element.removeEventListener(type, listener);
});
element.myEvents[type] = [];
});
}
I am not sure that this code works - it is just an example for demonstrating the idea.
You can also wrap these methods to addEventListener
and override the default behaviour. Just like:
Element.prototype.addEventListenerBase = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(type, listener, useCapture) {
// do the same
};
As for me, using jQuery library looks like the most clear solution here.
You will be able to attach an event this way:
$("#foo").on('click', function() {
});
and detach it in a simple way:
$("#foo").off('click');
I had the same problem and resolved it in different way.
$("#myelement").after($("#myelement")[0].outerHTML).remove()
You can check this code..hope it will help..
<a href="#" id="mydiv">click</a>
<a href="#" onclick="removeHandler()">remove</a>
<script>
document.getElementById("mydiv").addEventListener("click", myFunction);
function myFunction() {
alert('hello');
}
function removeHandler() {
document.getElementById("mydiv").removeEventListener("click", myFunction);
}
</script>
If you want to remove all event added to the element.
var el = document.getElementById('mydiv'),
elClone = el.cloneNode(true);
el.parentNode.replaceChild(elClone, el);