+ 1
How to remove addEventListener
I have a code…, div.addEventListener(“click”, (e) => {…}); ,… and I want to remove this type of event. How do I go about it?
8 Respuestas
+ 6
removeEventListener() method
https://www.w3schools.com/jsref/met_element_removeeventlistener.asp
+ 8
<p>You can do as follows and additional execute another function</p>
Check this box: <input type="checkbox" id="myCheckbox">
<p style="visibility:hidden;">Checking not allowed.</p>
<script>
document.getElementById("myCheckbox").addEventListener("click", function(event){
event.preventDefault()
alert("Checking prevented");
document.querySelectorAll("p")[0].style.backgroundColor = "red";
document.querySelectorAll("p")[1].style.visibility = "visible";
});
</script>
+ 5
Smith Anorue
how about using boolean flags to control whether or not the function gets called? It is similar to Mirielle 's suggestion on using boolean to provide alternative actions.
The point is you can just skip or disable callback functions with boolean flags instead of adding or removing it.
Here I mostly used checkboxes, but I also used a boolean variable to turn the callback functions on or off.
https://code.sololearn.com/WFK82dYPyQ4h/?ref=app
+ 4
Smith Anorue If you add the listener the way you do, using anonymous function, then you can't.
One solution would be convert that to a named function. This way you can use the removeEventListener().
The other solution, if you don't need to keep other event listeners possibly bound to an element, is to just clear all the listeners for an event.
0
It doesn’t work, what will I say the function is??
div.addEventListener(“click”, (e) => {…});
div.removeEventListener(“click”, <function>);
0
Completely share your code
0
freehand.addEventListener(“click”, (e) => {
clearTool();
freeTool();
});
line.addEventListener(“click”, (e) => {
clearTool();
lineTool();
});
function clearTool() {
//This is the part with the issue
canvas.removeEventListenter(“mousedown”, (e) => {});
canvas.removeEventListenter(“mouseup”, (e) => {});
canvas.removeEventListenter(“mousemove”, (e) => {});
}
function freeTool() {
canvas.addEventListenter(“mousedown”, (e) => {…});
canvas.addEventListenter(“mouseup”, (e) => {…});
canvas.addEventListenter(“mousemove”, (e) => {…});
}
function lineTool() {
canvas.addEventListenter(“mousedown”, (e) => {…});
canvas.addEventListenter(“mouseup”, (e) => {…});
}
Pardon me as I can’t put all the code here, it’s very much but this is tge vital part I’m having issues with.