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

7th Aug 2023, 6:15 PM
Smith Anorue
7 Respostas
7th Aug 2023, 6:46 PM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar
+ 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>
7th Aug 2023, 7:43 PM
JaScript
JaScript - avatar
+ 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
9th Aug 2023, 1:13 AM
Bob_Li
Bob_Li - avatar
+ 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.
8th Aug 2023, 4:31 PM
ЕĐČĐłĐ”ĐœĐžĐč
ЕĐČĐłĐ”ĐœĐžĐč - avatar
0
It doesn’t work, what will I say the function is?? div.addEventListener(“click”, (e) => {
}); div.removeEventListener(“click”, <function>);
7th Aug 2023, 6:52 PM
Smith Anorue
0
Completely share your code
7th Aug 2023, 6:54 PM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar
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.
7th Aug 2023, 7:11 PM
Smith Anorue