How to retrieve mouse position relative to element

Viewed 31

I'm getting an issue where event.clientX - getBoundingClientRect.left is returning a negative number. Someone posted a fiddle showing how it's meant to work Original fiddle

function getPosition(e) {
  var rect = e.target.getBoundingClientRect();
  var x = Math.floor(e.clientX - rect.left);
  var y = Math.floor(e.clientY - rect.top);
  return {
    x,
    y
  }
}

I updated it slightly to have it reproduce my issue here: Modified fiddle

Mousing over the blue box, I can get -1 to appear. Can someone explain where the rounding error is coming from please.

0 Answers
Related