Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Tracking mouse coordinates on page with WordPress admin-bar

While working for one of my client on his project to annotate images I dealt with a problem related to mouse coordinates when a user is logged-in in WordPress. WordPress shows an admin bar at top of the page due to which tracking mouse coordinates shifts by 28px vertically, height of admin bar. Tracking the mouse coordinates requires us to keep track of the canvas location and the mouse coordinates inside the canvas. Unfortunately, the canvas position is retrieved incorrectly if we just use positon() because it doesn't take into account the admin bar.

To fix the issue, I came up with a bit of a hack, but it works well with/without the admin bar. We can check for the presence of the admin bar and manually modify the mouse coordinates if it is present. Just add the following lines after you compute the mouse coordinates in canvas.

 // Wordpress admin bar fix.
if ($('#wpadminbar').length > 0) {  
  canvasY -= $('#wpadminbar').height();
}

Now the complete method to get the mouse coordinates looks like this. This works well in Chrome, Firefox, Safari and Opera.

function getMouseCoordinates(event) {  
  var totalOffsetX = 0; // The total x offset wrt document
  var totalOffsetY = 0; // The total y offset wrt document
  var canvasX = 0;      // X position of mouse in canvas 
  var canvasY = 0;      // Y position of mouse in canvas 

  // Iterate from canvas up the element heirarchy
  var currentElement = _canvas;
  do {
    totalOffsetX += currentElement.offsetLeft;
    totalOffsetY += currentElement.offsetTop;
  } while (currentElement = currentElement.offsetParent); // Update the current element

  // Get the mouse coordinates wrt canvas
  canvasX = event.pageX - totalOffsetX;  // event.pageX = X coordinate of mouse wrt page
  canvasY = event.pageY - totalOffsetY;  // event.pageY = Y coordinate of mouse wrt page

  // Wordpress admin bar fix.
  if ($('#wpadminbar').length > 0) {
    canvasY -= $('#wpadminbar').height();
  }

  return {
    x: canvasX,
    y: canvasY
  };
}