onMouseMove get mouse position [duplicate]
Asked Answered
S

4

21

In Javascript, within the Javascript event handler for onMouseMove how do I get the mouse position in x, y coordinates relative to the top of the page?

Sis answered 10/6, 2010 at 3:19 Comment(0)
L
29

if you can use jQuery, then this will help:

<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
    $("#divA").mousemove(function(e){
      var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
      var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
      $("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
      $("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
    });

</script>

here is pure javascript only example:

var tempX = 0;
  var tempY = 0;

  function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
      tempX = event.clientX + document.body.scrollLeft;
      tempY = event.clientY + document.body.scrollTop;
    }
    else {  // grab the x-y pos.s if browser is NS
      tempX = e.pageX;
      tempY = e.pageY;
    }  

    if (tempX < 0){tempX = 0;}
    if (tempY < 0){tempY = 0;}  

    document.Show.MouseX.value = tempX;//MouseX is textbox
    document.Show.MouseY.value = tempY;//MouseY is textbox

    return true;
  }
Lamarckian answered 10/6, 2010 at 3:34 Comment(5)
hmm, js example seems very similar to codelifter.com/main/javascript/capturemouseposition1.html except without the handy commentsKeir
id="#divA" and $("divA") -- someone was asleep when writing thisKeir
@Keir thanks for paying attention.Lamarckian
voted your answer up coz i ended up using part of it anyway :)Keir
What is the argument to getMouseXY(e) ?Stinnett
A
10

This is tried and works in all browsers:

function getMousePos(e) {
    return {x:e.clientX,y:e.clientY};
}

Now you can use it in an event like this:

document.onmousemove=function(e) {
    var mousecoords = getMousePos(e);
    alert(mousecoords.x);alert(mousecoords.y);
};

NOTE: The above function will return the mouse co-ordinates relative to the viewport, which is not affected by scroll. If you want to get co-ordinates including scroll, then use the below function.

function getMousePos(e) {
    return {
        x: e.clientX + document.body.scrollLeft,
        y: e.clientY + document.body.scrollTop
    };
}
Allyn answered 25/11, 2016 at 16:26 Comment(0)
J
6

It might be a bit overkill to use d3.js just for finding mouse coordinates, but they have a very useful function called d3.mouse(*container*). Below is an example of doing what you want to do:

var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
  .on('mousemove', function()
    {
      coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
                                    // the top of the page (because I selected
                                    // 'html')
    });

In the above case, the x-coordinate would be coordinates[0], and the y-coordinate would be coordinates[1]. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging 'html' with the tag (e.g. 'body'), class name (e.g. '.class_name'), or id (e.g. '#element_id').

Jesu answered 27/2, 2013 at 22:3 Comment(1)
+1, but Fair Warning: This approach is a little too sluggish for use against onmousemove. I already had d3.js in my project so I tried it, but it's just not spry enough for my use case.Stilbestrol
T
4

Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-

var whereAt= (function(){
    if(window.pageXOffset!= undefined){
        return function(ev){
            return [ev.clientX+window.pageXOffset,
            ev.clientY+window.pageYOffset];
        }
    }
    else return function(){
        var ev= window.event,
        d= document.documentElement, b= document.body;
        return [ev.clientX+d.scrollLeft+ b.scrollLeft,
        ev.clientY+d.scrollTop+ b.scrollTop];
    }
})()

document.ondblclick=function(e){alert(whereAt(e))};

Tarnation answered 10/6, 2010 at 4:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.