Search code examples
javascripteventslistenerdom-events

Why doesn't removeEventListener function?


var mouseListener = button2.addEventListener("mouseover", function (e) {
count++;
...
if(count > 5) button2.removeEventListener("mouseover", mouseListener);
});

I don't why the code doesn't work? How do I use the removeEventListener () in Javascript?


Solution

  • The listener is the function you are passing in the addEventListener function.

    var mouseListener = function (e) {
        count++;
        ...
        if ( count > 5 ) {
            button2.removeEventListener("mouseover", mouseListener);
        }
    }
    
    button2.addEventListener("mouseover", mouseListener);
    

    Documentation:
    https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener