Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove event listener in JavaScript

I add an event listener to an 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
    //...
}

The event listener is not being removed, though. When I click on one of the elements, the code of myfunction is executed again. How can I remove the event listener to prevent the clicked element from being clicked again?

PS: I do not use jQuery.

like image 926
reggie Avatar asked Jan 12 '12 19:01

reggie


3 Answers

I believe you're almost there, but you have to pass the listener to removeEventListener, not the event itself. So try:

target.removeEventListener('click', myFunction, false);
like image 114
bfavaretto Avatar answered Nov 04 '22 18:11

bfavaretto


Use element.removeEventListener(type, listener, useCapture) Remember to use that on the same element, and give it the exact same parameters as you did for adding.

One excellent way to code this would be to make a function that stores the listener details in a variable, mimicking how setTimeout() works for instance, and adding that to the element prototype. Here's 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;
}

That will add a method to all HTML nodes that already can accept event listners, and allow you to do this.

var a=element.eventListener('click', myFunction, false); //to add
element.eventListener(a); //to remove
like image 24
TERMtm Avatar answered Nov 04 '22 16:11

TERMtm


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. Reference to the event handler function to remove. You need to pass what listener you want to remove.

like image 2
Luke Shaheen Avatar answered Nov 04 '22 17:11

Luke Shaheen