views:

529

answers:

2

I have a function in javascript that moves one div depending on the mouse position. This function is set on a setInterval() function and executed every second. I need to capture the mouse position like this:

function mousemov() {
  document.getElementById("myDiv").style.left = Event.clientX; //don't work
}

window.onload = function() {
  setInterval("mousemov()",1000);
}

Ps: I cannot use the mousemove event because the function must be executed even if the mouse is stopped.

Thanks for helps!

A: 

well, if you listen to mouse move for the document and save its location, then, whenever you want, e.g. every second in your case you have the latest registered mouse position.

this is a jquery example

$(document).ready(function()
 {
  $().mousemove(function(e)
   {
       window.mouseX = e.pageX;
       window.mouseY = e.pageY;
  });
});

and your mousemove function would be

function mousemov() { 
    document.getElementById("myDiv").style.left = window.mouseX;
}
Tzury Bar Yochay
+2  A: 

The only time that you can access the event object is during the execution of an event handler. So what you need to do is create an OnMouseMove event on the document and store the mouse coordinates in a globally accessible object. You can then access these values from anywhere else in your script to determine the mouse position.

Here is an example (you're not using jQuery, so this is straight DOM code):

document.onmousemove = function(e) {
    var event = e || window.event;
    window.mouseX = event.clientX;
    window.mouseY = event.clientY;
}

function mousemov() {
    document.getElementById("myDiv").style.left = window.mouseX;
}

window.onload = function() {
    setInterval(mousemov, 1000);
}

I should make the note that clientX and clientY don't take scrolling into account. You'll need to retrieve the scrolling offsets and apply them to the returned values.

Jon Benedicto
+1. You may want to explain that an event object is not created unless you capture an event. So what he essentially need to do is capture the mousemove event and store the mouse position in a globally accessible place and then use that value in the interval function.
Chetan Sastry
Also, `setInterval("functionName()", 1000)` is not a good practice (it is similar to `eval()`). Go for either `setInterval(mousemov, 1000)` or `setInterval(function() {mousemove()}, 1000)`
Chetan Sastry
FYI `clientX`/`clientY` exclude any document scroll that may exist.
Crescent Fresh
it's works....thank u
rizidoro
Thanks Chetan and crescentfresh - I've updated the answer to reflect your comments.
Jon Benedicto