The code below creates a new button element with the text "Download" and an ID of "download", and appends it as a child element of the element with an ID of "container".
When the button is clicked the container’s onclick is also triggered. I tried to remove it with
removeEventListener()
without success.
document.getElementById('download').removeEventListener("onclick", myclick);
document.getElementById('download').removeEventListener("click", myclick);
document.getElementById('download').removeEventListener("click", myclick, true);
function cleanup(elem) {
for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
elem[t] = null;
console.log('cleanup removed listener from '+elem.nodeName,t);
}
for (let t of elem.all_handlers || []) {
elem.removeEventListener(t.typ, t.fn, t.opt);
console.log('cleanup removed listener from '+elem.nodeName,t.typ);
}
}
var el = document.getElementById('download');
cleanup(el);
I also tried all of those answers and none of them removed the onclick. (e.g. cloning etc.)
PS: the HTML code cannot be modified because it’s part of a framework.
$(document).ready(function() {
$('#container').append(
$(document.createElement('button')).prop({
type: 'button',
innerHTML: 'Download',
id : 'download'
})
);
// I placed the code to remove the event listener here
});
function myclick(e) {
console.log('myclick');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html id="container" onclick="myclick(event)">
</html>
3
Answers
You are removing the eventlistener from #download, shouldn’t you remove it from #container?
or
if you want to prevent myclick function to be called when the button is pressed, you can actually add onclick event to the button:
Removing the event listener for the parent element isn’t the best way to do this. Instead, the child element’s event listener should call
event.stopPropagation()
to prevent the event from bubbling up to parent elements. I recommend reading up online about Event Bubbling in JavaScript.