addEventListener mousemove on document ready

31,434
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.

Share:
31,434
Björn Reinhardt
Author by

Björn Reinhardt

Updated on December 22, 2020

Comments

  • Björn Reinhardt
    Björn Reinhardt over 3 years

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