Blake O'Hare .com

Getting the Position of the Mouse in JavaScript

Nothing makes me pull my hair out more than the browser-specific nuances of JavaScript. Even more annoying is dealing with mouse position. So as a public service, I offer this page which has JavaScript examples for finding the coordinates of the mouse for different reference points.

You're welcome.

Finding the position of the mouse relative to the screen


function findScreenCoords(mouseEvent)
{
  var xpos;
  var ypos;
  if (mouseEvent)
  {
    //FireFox
    xpos = mouseEvent.screenX;
    ypos = mouseEvent.screenY;
  }
  else
  {
    //IE
    xpos = window.event.screenX;
    ypos = window.event.screenY;
  }
  document.getElementById("screenCoords").innerHTML = xpos + ", " + ypos;
}
document.getElementById("screenBox").onmousemove = findScreenCoords;

 


Finding the position of the mouse relative to the document origin


function findDocumentCoords(mouseEvent)
{
  var xpos
  var ypos;
  if (mouseEvent)
  {
    //FireFox
    xpos = mouseEvent.pageX;
    ypos = mouseEvent.pageY;
  }
  else
  {
    //IE
    xpos = window.event.x + document.body.scrollLeft - 2;
    ypos = window.event.y + document.body.scrollTop - 2;
  }
  document.getElementById("documentCoords").innerHTML = xpos + ", " + ypos;
}

document.getElementById("documentBox").onmousemove = findDocumentCoords;

 


Finding the position of the mouse relative to the document view frame thingy



function findViewCoords(mouseEvent)
{
  var xpos;
  var ypos;
  if (mouseEvent)
  {
    //FireFox
    xpos = mouseEvent.pageX - document.body.scrollLeft;
    ypos = mouseEvent.pageY - document.body.scrollTop;
  }
  else
  {
    //IE
    xpos = window.event.x + 2;
    ypos = window.event.y + 2;
  }
  document.getElementById("viewCoords").innerHTML = xpos + ", " + ypos;
}
document.getElementById("viewBox").onmousemove = findViewCoords;

 


Finding the position of the mouse within an object


function findObjectCoords(mouseEvent)
{
  var obj = document.getElementById("objectBox");
  var obj_left = 0;
  var obj_top = 0;
  var xpos;
  var ypos;
  while (obj.offsetParent)
  {
    obj_left += obj.offsetLeft;
    obj_top += obj.offsetTop;
    obj = obj.offsetParent;
  }
  if (mouseEvent)
  {
    //FireFox
    xpos = mouseEvent.pageX;
    ypos = mouseEvent.pageY;
  }
  else
  {
    //IE
    xpos = window.event.x + document.body.scrollLeft - 2;
    ypos = window.event.y + document.body.scrollTop - 2;
  }
  xpos -= obj_left;
  ypos -= obj_top;
  document.getElementById("objectCoords").innerHTML = xpos + ", " + ypos;
}
document.getElementById("objectBox").onmousemove = findObjectCoords;