Jonas
Jonas

Reputation: 7945

Mousemove Event: mouse position relative to parent element

I have a div that I want to listen to the mousemove event to see the offset between the mouse and the top of the div (so I use event.layerY). Inside this div I have another div.

The problem is when I move my mouse over this inner div, my mousemove event listens to the inner div and not the outer div where I set the listener to. Meaning event.layerY will give me the offset to the inner div and not the outer div.

This is my code:

this.draglistener = this.renderer.listen(this.container.nativeElement, 'mousemove', e => {
        e.stopPropagation();
    });

As you can see I tired stopPropagation()but that doesn't work. I also tried this:

if (e.target !== this.container.nativeElement) {
            return;
}

But this way it just stops listening to the event when moving over the inner div. So thats not working too.

Also I can't do pointer-events: none; for the inner div because I need to listen to some other events on this div.

Any Ideas?

Upvotes: 2

Views: 3878

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73771

To get the mouse position relative to the outer div, subtract the client position of the outer div from the client position of the mouse. A template reference variable outerDiv can be used to pass the outer element to the event handler.

<div #outerDiv (mousemove)="onMouseMove($event, outerDiv)">
  <div class="innerDiv">
  </div>
</div>

In the event handler, the client mouse position is obtained with event.clientX and event.clientY, and the outer div client position is obtained with outerDiv.getBoundingClientRect().

onMouseMove(event: MouseEvent, outerDiv: HTMLElement) {
  const bounds = outerDiv.getBoundingClientRect();
  const posX = event.clientX - bounds.left;
  const posY = event.clientY - bounds.top;
  console.log(posX, posY);
}

See this stackblitz for a demo.

Upvotes: 3

Related Questions