Javascript removeEventListener not working - event listener remains

10,515

Solution 1

When calling removeEventListener, you have to give it the same function instance than to addEventListener:

var lb = document.body;

var callback = function(event){
    keyPress(event.keyCode)
};

if(lb.addEventListener){    
    lb.addEventListener('keyup', callback, false);
}

//In another function.

if(document.body.removeEventListener){
    document.body.removeEventListener('keyup', callback, false);
}

jQuery makes it easier to deal with this, thanks to its namespaced events feature:

$(lb).on('keyup.my_namespace', function () { ... })

// later

$(lb).off('keyup.my_namespace');

Solution 2

You need to name the handler function in order to reference it later when removing the listener:

lb.addEventListener('keyup', 
function keyup(event){ // assigns the handler to "keyup"
    keyPress(event.keyCode)
}, false);

document.body.removeEventListener('keyup', keyup, false);

Solution 3

you cant remove an anonymous function with removeEventListener, instead use the function name. e.g:

if(lb.addEventListener){    
    lb.addEventListener('keyup', myFunction, false);
}

//In another function.

if(document.body.removeEventListener){
    document.body.removeEventListener('keyup', myFunction, false);
} 

the new function:

function myFunction(e){
    var keyCode = e.keyCode;

}
Share:
10,515
Josh Dredge
Author by

Josh Dredge

Updated on June 04, 2022

Comments

  • Josh Dredge
    Josh Dredge almost 2 years

    I've looked at a few ways around this, but I can't really tell, my code is:

    lb = document.body;
    
    if(lb.addEventListener){    
        lb.addEventListener('keyup',
        function(event){
            keyPress(event.keyCode)
        }, false);
    }
    
    //In another function.
    
    if(document.body.removeEventListener){
        document.body.removeEventListener('keyup', function(event){event.keyCode}, false);
    } 
    

    The remove code is not working, haven't tried a great deal of solutions yet but its the last thing on my script and I just want it done.

    Thank you all