Link to home
Start Free TrialLog in
Avatar of clickclickbang
clickclickbang

asked on

Help With Mouse Cursor X/Y Position

Experts, I need some help with a script I am using to get the X & Y of the mouse cursor.

I am using the following script:

// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all ? true : false

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)

// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;

// Temporary variables to hold mouse x-y pos.s
var CursorX = 0
var CursorY = 0

// Main function to retrieve mouse x-y pos.s

function getMouseXY(e) {
  if (document.body)
  { // grab the x-y pos.s if browser is IE
    CursorX = event.clientX + document.body.scrollLeft
    CursorY = event.clientY + document.body.scrollTop
  }
  else
  {  // grab the x-y pos.s if browser is NS
    CursorX = e.pageX
    CursorY = e.pageY
  }
  // catch possible negative values in NS4
  if (CursorX < 0)
  {
    CursorX = 0
  }
 
  if (CursorY < 0)
  {
    CursorY = 0
  }
  return true
}

The problem with this script is that it does not seem to take in account the scroll position on the page. It works fine as long as the page is not scrolled. Once the page is scrolled the script returns values of the scrolled "viewable" area of the page and not the true x or y coordinates.

Can someone help me out and/or recommend another Mouse X/Y script I can use?

Problem occurs in IE7 but works in Firefox 1. The script is in a JS file and not directly on the page.

Thanks for your help!

~ C

Avatar of BraveBrain
BraveBrain
Flag of Norway image

Try this one

    function getMouseXY(evt) {
      evt = evt || event;
      cursorX = evt.pageX || evt.clientX + document.body.scrollLeft;
      cursorY = evt.pageY || evt.clientY + document.body.scrollTop;
      cursorX = (cursorX<0) ? 0 : cursorX;
      cursorY = (cursorY<0) ? 0 : cursorY;
      document.title = 'cursorX/cursorY: '+cursorX+'/'+cursorY;
      return true;
    }
    document.onmousemove = getMouseXY;
btw, this line
document.title = 'cursorX/cursorY: '+cursorX+'/'+cursorY;
is just so you can see the x/y positions in the document title while testing.
Avatar of clickclickbang
clickclickbang

ASKER

BB,
Thanks for the script. Again it works fine in FireFox but IE7 sets the position based upon the scroll window and not the actual page. Any idea of why this is happening?

~ C
ASKER CERTIFIED SOLUTION
Avatar of BraveBrain
BraveBrain
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for your help!