How can I get the mouse coordinates relative to a parent div? Javascript

GriffLab picture GriffLab · Apr 22, 2013 · Viewed 29.9k times · Source

I currently have a div structured with other elements inside of it.

Something similar to below;

<div id="container" style="position: relative; width: 500px; height: 500px;">
     <div style="position: absolute; left: 50px; top: 50px;"></div>
     <div style="position: absolute; left: 100px; top: 100px;"></div>
</div>

I am trying to get the mouse position relative to the div with the id container.

So far I have this;

function onMousemove(event) {

    x = event.offsetX;
    y = event.offsetY;
};

var elem = document.getElementById("container");
elem.addEventListener("mousemove", onMousemove, false);

This works fine if the div with the id container has no children. When the container div has children it gets the mouse co-ordinates relative to the child rather than the parent.

What I mean by this is if the mouse was at a position of x: 51, y: 51 relative to the parent div, it would actually return x: 1, y: 1 relative to the child div, using the html given above.

How can I achieve what I want, no libraries please.

EDIT

tymeJV has kindly made a jsfiddle of what is happening above.

http://jsfiddle.net/N6PJu/1

Answer

Nikita Volkov picture Nikita Volkov · Oct 26, 2015

The accepted answer didn't work for me in Chrome. Here's how I solved it:

function relativeCoords ( event ) {
  var bounds = event.target.getBoundingClientRect();
  var x = event.clientX - bounds.left;
  var y = event.clientY - bounds.top;
  return {x: x, y: y};
}