In Javascript, how can I get the position of the mouse within an element when it's clicked?
September 17, 2004 8:35 AM   Subscribe

Javascript Help: Getting position of mouse within an element when that element is clicked on. [more inside]

For a click on a given element, I want to be able capture the x/y coordinates of the mouse -- not relative to the top of the document, but rather, relative to the top left corner of the clicked-on element.

So far, here's what I've got:

It seems to work in Gecko-based browsers, and IE/Win.

It seems to break badly in Safari, grabbing what is apparently instead the viewport position of the mouse. Also, on IE/Mac, it breaks if there's any scrolling done on the page (try resizing the window so that it's smaller than the sample image, then scrolling down, and then clicking).

Any ideas what I can do to make it work better for the Mac browsers? Also, any other platforms which you observe it breaking under?
posted by weston to Computers & Internet (3 answers total)
Oh. Link to the above url.

Also, here's the code to the basic function I'm using:

function getClickCoordsWithinTarget(event)
  var coords = { x: 0, y: 0};

  if(!event) // then we're in a non-DOM (pro'ly IE) browser
    event = window.event;
    coords.x = event.offsetX;
    coords.y = event.offsetY;
  else // we assume DOM modeled javascript
    var Element = ;
    var CalculatedTotalOffsetLeft = 0;
    var CalculatedTotalOffsetTop = 0 ;

    while (Element.offsetParent)
      CalculatedTotalOffsetLeft += Element.offsetLeft;
      CalculatedTotalOffsetTop += Element.offsetTop;
      Element = Element.offsetParent ;

    coords.x = event.pageX - CalculatedTotalOffsetLeft;
    coords.y = event.pageY - CalculatedTotalOffsetTop;

  return coords;

Basically, if it's IE, I use IE specific properties of the event, offsetX/Y, which is supposed to do the job. If it's Gecko (and presumably any DOM browser), the script crawls up the DOM tree, adding up the left/top offsets to get the position of the clicked-on element, and then subtracts that amount from the document position coordinates.

Is Safari not DOM compliant enough? And what's up with IE/Mac? Are some of my assumptions broken?
posted by weston at 8:58 AM on September 17, 2004

Um... Please? Anyone?

Maybe I should ammend my question -- does anyone know where I can find good javascript information specifically related to Safari and IE/Mac?
posted by weston at 6:09 PM on September 17, 2004

Sorry weston, I don't know Safari well enough to help but has good mouse position scripts.
posted by holloway at 11:35 PM on September 17, 2004

« Older How do you organize your electronic notebook?   |   Baseboards Newer »
This thread is closed to new comments.