Remove event listener in JavaScript

reggie picture reggie · Jan 12, 2012 · Viewed 29.2k times · Source

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.

Answer

bfavaretto picture bfavaretto · Jan 12, 2012

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);