Search code examples
javascriptdom-eventsmouseeventaddeventlistener

Remove event listeners Javascript


I'm trying to understand how to add and remove event listeners using Javascript, but it's not working like I expect.

What I thought should happen is when I move the mouse over the canvas it starts console logging the x- and y-coords of my mouse, which it does, but I also expect when i click on the mouse, it should stop logging the coords, which it doesn't...it just keeps console logging the coords until i refresh the page.

This is my html:

<!DOCTYPE html>
<html>
  <head>
    <title> My Canvas </title>
    <link rel="stylesheet" type="text/css" href="test_eventhandlers.css">
    <script src="test_eventhandlers.js" type="text/javascript"></script>    
  </head>
  <body>
    <canvas id="myCanvas" width="640" height="360"></canvas>
  </body>
</html>

This is my javascript:

window.onload = function(){
  var myCanvas = document.getElementById("myCanvas");
  myCanvas.addEventListener('mousemove', consoleCoordsMouseMove, false);
  myCanvas.removeEventListener('click', consoleCoordsMouseMove, false);

  function consoleCoordsMouseMove(){
    var x=event.x;
    var y=event.y;
    console.log("mousemove: " + x + " and " + y);
  }
};

Why isn't this working? I've tried a few other variations of this and nothing seems to work.


Solution

  • This should work:

    var myCanvas = document.getElementById("myCanvas");
    myCanvas.addEventListener('mousemove', consoleCoordsMouseMove, false);
    myCanvas.addEventListener('click', function () {
        this.removeEventListener('mousemove', consoleCoordsMouseMove, false);
    }, false);
    
    function consoleCoordsMouseMove(e) {
        var x = event.x;
        var y = event.y;
        console.log(x + ',' + y);
    }
    

    http://jsfiddle.net/Nmcgt/1/