Delete Event Listener in JavaScript

I add an event listener to the element:

/* sitepoint.com/javascript-this-event-handlers */ function AttachEvent(element, type, handler){ if (element.addEventListener){ element.addEventListener(type, handler, false); }else{ element.attachEvent("on"+type, handler); } } window.addEventListener("load", function() { var els = getElementsByClassName('name', 'img'); var elsnum = els.length; if(elsnum) //found { var i = 0; for(i=0; i < elsnum; i++) { var the_els = els[i]; AttachEvent(the_els, "click", myfunction); } } }, false); 

Later in myfunction I want to remove the handler again to prevent duplicate clicks:

 function myfunction(e) { e = e || window.event; var target = e.target || e.srcElement; //more code //... //remove click handler target.removeEventListener('click', e, false); //more code //... } 

However, the event listener is not deleted. When I click on one of the elements, the myfunction code myfunction executed again. How to remove an event listener to prevent clicked element from re-clicking?

PS: I do not use jQuery.

+4
source share
3 answers

I believe you are almost there, but you should pass the removeEventListener to the listener, not the event itself. So try:

 target.removeEventListener('click', myFunction, false); 
+7
source

Use element.removeEventListener(type, listener, useCapture) Remember to use this on one element and give it the same parameters as for adding.

One excellent coding method would be to create a function that stores listener details in a variable, mimicking how setTimeout() works, and adding this to the element's prototype. Here is an example function.

 HTMLElement.prototype.eventListener= function(type, func, capture){ if(typeof arguments[0]=="object"&&(!arguments[0].nodeType)){ return this.removeEventListener.apply(this,arguments[0]); } this.addEventListener(type, func, capture); return arguments; } 

This will add a method to all HTML nodes that can already accept event lists, and allow that.

 var a=element.eventListener('click', myFunction, false); //to add element.eventListener(a); //to remove 
+4
source

http://www.quirksmode.org/js/events_advanced.html

To remove an event handler, use the removeEventListener() method.

Also see http://help.dottoro.com/ljahxbsx.php

object.removeEventListener (eventName, listener, useCapture);

listener - required. A reference to the event handler function to delete. You need to pass which listener you want to delete.

+2
source

Source: https://habr.com/ru/post/1390711/


All Articles