[javascript] Javascript - Track mouse position

I am hoping to track the position of the mouse cursor, periodically every t mseconds. So essentially, when a page loads - this tracker should start and for (say) every 100 ms, I should get the new value of posX and posY and print it out in the form.

I tried the following code - but the values do not get refreshed - only the initial values of posX and posY show up in the form boxes. Any ideas on how I can get this up and running ?

<html>
<head>
<title> Track Mouse </title>
<script type="text/javascript">
function mouse_position()
{
    var e = window.event;

    var posX = e.clientX;
    var posY = e.clientY;

    document.Form1.posx.value = posX;
    document.Form1.posy.value = posY;

    var t = setTimeout(mouse_position,100);

}
</script>

</head>

<body onload="mouse_position()">
<form name="Form1">
POSX: <input type="text" name="posx"><br>
POSY: <input type="text" name="posy"><br>
</form>
</body>
</html>

This question is related to javascript

The answer is


I don't have enough reputation to post a comment reply, but took TJ Crowder's excellent answer and fully defined the code on a 100ms timer. (He left some details to the imagination.)

Thanks OP for the question, and TJ for the answer! You're both a great help. Code is embedded below as a mirror of isbin.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Example</title>_x000D_
  <style>_x000D_
    body {_x000D_
      height: 3000px;_x000D_
    }_x000D_
    .dot {_x000D_
      width: 2px;_x000D_
      height: 2px;_x000D_
      background-color: black;_x000D_
      position: absolute;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
<body>_x000D_
<script>_x000D_
(function() {_x000D_
    "use strict";_x000D_
    var mousePos;_x000D_
_x000D_
    document.onmousemove = handleMouseMove;_x000D_
    setInterval(getMousePosition, 100); // setInterval repeats every X ms_x000D_
_x000D_
    function handleMouseMove(event) {_x000D_
        var eventDoc, doc, body;_x000D_
_x000D_
        event = event || window.event; // IE-ism_x000D_
_x000D_
        // If pageX/Y aren't available and clientX/Y are,_x000D_
        // calculate pageX/Y - logic taken from jQuery._x000D_
        // (This is to support old IE)_x000D_
        if (event.pageX == null && event.clientX != null) {_x000D_
            eventDoc = (event.target && event.target.ownerDocument) || document;_x000D_
            doc = eventDoc.documentElement;_x000D_
            body = eventDoc.body;_x000D_
_x000D_
            event.pageX = event.clientX +_x000D_
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -_x000D_
              (doc && doc.clientLeft || body && body.clientLeft || 0);_x000D_
            event.pageY = event.clientY +_x000D_
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -_x000D_
              (doc && doc.clientTop  || body && body.clientTop  || 0 );_x000D_
        }_x000D_
_x000D_
        mousePos = {_x000D_
            x: event.pageX,_x000D_
            y: event.pageY_x000D_
        };_x000D_
    }_x000D_
    function getMousePosition() {_x000D_
        var pos = mousePos;_x000D_
  _x000D_
        if (!pos) {_x000D_
            // We haven't seen any movement yet, so don't add a duplicate dot _x000D_
        }_x000D_
        else {_x000D_
            // Use pos.x and pos.y_x000D_
            // Add a dot to follow the cursor_x000D_
            var dot;_x000D_
            dot = document.createElement('div');_x000D_
            dot.className = "dot";_x000D_
            dot.style.left = pos.x + "px";_x000D_
            dot.style.top = pos.y + "px";_x000D_
            document.body.appendChild(dot);_x000D_
        }_x000D_
    }_x000D_
})();_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


What I think that he only wants to know the X/Y positions of cursor than why answer is that complicated.

_x000D_
_x000D_
// Getting 'Info' div in js hands_x000D_
var info = document.getElementById('info');_x000D_
_x000D_
// Creating function that will tell the position of cursor_x000D_
// PageX and PageY will getting position values and show them in P_x000D_
function tellPos(p){_x000D_
  info.innerHTML = 'Position X : ' + p.pageX + '<br />Position Y : ' + p.pageY;_x000D_
}_x000D_
addEventListener('mousemove', tellPos, false);
_x000D_
* {_x000D_
  padding: 0:_x000D_
  margin: 0;_x000D_
  /*transition: 0.2s all ease;*/_x000D_
  }_x000D_
#info {_x000D_
  position: absolute;_x000D_
  top: 10px;_x000D_
  right: 10px;_x000D_
  background-color: black;_x000D_
  color: white;_x000D_
  padding: 25px 50px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  _x000D_
  <body>_x000D_
    <div id='info'></div>_x000D_
        </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_


ES6 based code:

let handleMousemove = (event) => {
  console.log(`mouse position: ${event.x}:${event.y}`);
};

document.addEventListener('mousemove', handleMousemove);

If you need throttling for mousemoving, use this:

let handleMousemove = (event) => {
  console.warn(`${event.x}:${event.y}\n`);
};

let throttle = (func, delay) => {
  let prev = Date.now() - delay;
  return (...args) => {
    let current = Date.now();
    if (current - prev >= delay) {
      prev = current;
      func.apply(null, args);
    }
  }
};

// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));

here is example


If just want to track the mouse movement visually:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
</head>_x000D_
<style type="text/css">_x000D_
* { margin: 0; padding: 0; }_x000D_
html, body { width: 100%; height: 100%; overflow: hidden; }_x000D_
</style>_x000D_
<body>_x000D_
<canvas></canvas>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var_x000D_
canvas    = document.querySelector('canvas'),_x000D_
ctx       = canvas.getContext('2d'),_x000D_
beginPath = false;_x000D_
_x000D_
canvas.width  = window.innerWidth;_x000D_
canvas.height = window.innerHeight;_x000D_
_x000D_
document.body.addEventListener('mousemove', function (event) {_x000D_
 var x = event.clientX, y = event.clientY;_x000D_
_x000D_
 if (beginPath) {_x000D_
  ctx.lineTo(x, y);_x000D_
  ctx.stroke();_x000D_
 } else {_x000D_
  ctx.beginPath();_x000D_
  ctx.moveTo(x, y);_x000D_
  beginPath = true;_x000D_
 }_x000D_
}, false);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Here's a solution, based on jQuery and a mouse event listener (which is far better than a regular polling) on the body:

$("body").mousemove(function(e) {
    document.Form1.posx.value = e.pageX;
    document.Form1.posy.value = e.pageY;
})

onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}

Open your console (Ctrl+Shift+J), copy-paste the code above and move your mouse on browser window.


Irrespective of the browser, below lines worked for me to fetch correct mouse position.

event.clientX - event.currentTarget.getBoundingClientRect().left event.clientY - event.currentTarget.getBoundingClientRect().top


Here is the simplest way to track your mouse position

Html

<body id="mouse-position" ></body>

js

document.querySelector('#mouse-position').addEventListener('mousemove', (e) => {
        console.log("mouse move X: ", e.clientX);
        console.log("mouse move X: ", e.screenX);


    }, );

know more


We recently had to find the current x,y position to enumerate elements over which the cursor is hovering independent of z-index. We ended up just attaching a mousemove event listener to document e.g.,

_x000D_
_x000D_
function findElements(e) {
  var els = document.elementsFromPoint(e.clientX, e.clientY);

  // do cool stuff with els
  console.log(els);

  return;
}

document.addEventListener("mousemove", findElements);
_x000D_
_x000D_
_x000D_


Here’s a combination of the two requirements: track the mouse position, every 100 milliseconds:

var period = 100,
    tracking;

window.addEventListener("mousemove", function(e) {
    if (!tracking) {
        return;
    }

    console.log("mouse location:", e.clientX, e.clientY)
    schedule();
});

schedule();

function schedule() {
    tracking = false;

    setTimeout(function() {
        tracking = true;
    }, period);
}

This tracks & acts on the mouse position, but only every period milliseconds.


I believe that we are overthinking this,

_x000D_
_x000D_
function mouse_position(e)_x000D_
{_x000D_
//do stuff_x000D_
}
_x000D_
<body onmousemove="mouse_position(event)"></body>
_x000D_
_x000D_
_x000D_


Just a simplified version of @T.J. Crowder and @RegarBoy's answers.

Less is more in my opinion.

Check out onmousemove event for more info about the event.

Image mouse tracker

There's a new value of posX and posY every time the mouse moves according to the horizontal and vertical coordinates.

<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Example Mouse Tracker</title>
      <style>    
        body {height: 3000px;}
        .dot {width: 2px;height: 2px;background-color: black;position: absolute;}
      </style>
    </head>
    <body>
    <p>Mouse tracker</p>
    <script>
    onmousemove = function(e){
        //Logging purposes
        console.log("mouse location:", e.clientX, e.clientY);

        //meat and potatoes of the snippet
        var pos = e;
        var dot;
        dot = document.createElement('div');
        dot.className = "dot";
        dot.style.left = pos.x + "px";
        dot.style.top = pos.y + "px";
        document.body.appendChild(dot);
    }      
    </script>
    </body>
    </html>