+ 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 Answers
+ 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.