6

Newbie-question I suppose.

The following code is part of a function that I call on document ready. It is intended to permanently return the values of the current mouse position whenever the mouse is moved.

The odd thing that is happening: Moving the mouse on document ready doesn't log anything to the console. I know the mouse_monitor-function works though because I use this function in another "mousedown"-eventlistener and it then logs the current mouse-position to the console.

//Mouse Monitor

    canvas.addEventListener('mousemove', mouse_monitor, false);


//Mouse Monitor Request
    var mouse = new Array();
    var mouse_monitor = function(e) {
        var canvasOffset=$("#canvas").offset();
        var offsetX=canvasOffset.left;
        var offsetY=canvasOffset.top;
        mouse.x = e.pageX - offsetX;
        mouse.y = e.pageY - offsetY;
        return mouse;
        console.log(mouse);
    }
Björn Reinhardt
  • 61
  • 1
  • 1
  • 2
  • Also note that if the addEventListener take place before the assignment of mouse_monitor the addEventListener doesn't add any event – Loris Jun 08 '13 at 11:56

1 Answers1

6
return mouse;

Any statements after that line won't be executed.

Okay, then get something working and add to it/modify it incrementally:

var mouse_monitor = function(e) {
  var x = e.pageX;
  var y = e.pageY;
  console.log(x, y);
}

window.onload = function() {
  this.addEventListener('mousemove', mouse_monitor);
}

But you mentioned "document ready", so if you are using jquery you should avoid using addEventListener() because it's not cross browser:

var mouse_monitor = function(e) {
  var x = e.pageX;
  var y = e.pageY;
  console.log(x, y);
}

$(document).ready( function() {
  $(this).on('mousemove', mouse_monitor);
});

Another approach is to console.log() all variables and their values leading up to the failed code to determine which values are not as they should be.

7stud
  • 46,922
  • 14
  • 101
  • 127