Monday, April 11, 2011

Possible to get the current mouse coords with Javascript?

Possible to get the current mouse coords with Javascript?

From stackoverflow
  • This can be done. Just googled and got the following code

    if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.clientX + document.body.scrollLeft;
        tempY = event.clientY + document.body.scrollTop;
    }
    
  • you can get mouse coordinats in browser like this.

  • Here is a full example: here

  • Source: http://javascript.internet.com/page-details/mouse-coordinates.html

    <form name="Show">
    X <input type="text" name="MouseX" value="0" size="4"><br>
    Y <input type="text" name="MouseY" value="0" size="4"><br>
    </form>
    
    <script language="JavaScript">
    var IE = document.all?true:false;
    if (!IE) document.captureEvents(Event.MOUSEMOVE)
    document.onmousemove = getMouseXY;
    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;
    document.Show.MouseY.value = tempY;
    return true;
    }
    </script>
    
    Andrew G. Johnson : Modified a bit but worked great on my tests: IE6, IE7, & FF3
  • Here is a compact function with a demonstration, it returns value with coordinates in .x and .y:

    function mouseCoords(ev){
     // from http://www.webreference.com/programming/javascript/mk/column2/
     if(ev.pageX || ev.pageY){
      return {x:ev.pageX, y:ev.pageY};
     }
     return {
      x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
      y:ev.clientY + document.body.scrollTop  - document.body.clientTop
     };
    }
    

    (I found quirksmode to be a good resource of JavaScript wisdom. Here is the some background of the function in case you want to dig deeper.)

0 comments:

Post a Comment