How to remove addEventListener | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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
Sakshi - 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
Sakshi - 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