+ 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?
7 Respostas
+ 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.