Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener mousemove on document ready

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);
    }
like image 648
Björn Reinhardt Avatar asked Jun 08 '13 11:06

Björn Reinhardt


People also ask

What is document body addEventListener?

Definition and Usage. The addEventListener() method attaches an event handler to a document.

What is onmousemove?

The onmousemove event occurs when the pointer is moving while it is over an element.

How often does Mousemove fire?

The mousemove event frequency is implementation specific, and not defined by any specification. A user agent MUST dispatch this event when a pointing device is moved while it is over an element.


1 Answers

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.

like image 186
7stud Avatar answered Nov 11 '22 09:11

7stud