Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouse coordinates relative to currentTarget in React in event handler

I have an outer div which catches onWheel mouse events. In the handler I would like to know the mouse pointer coordinates relative to the outer div. For example:

constructor() {
  this.handleWheel = this.handleWheel.bind(this);
}

handleWheel(event) {
  // how do I get mouse position relative to the outer div here?
}

render() {
  return (
    <div onWheel={this.handleWheel}>
      ...
      <img src="..." />
      ...
    </div>
  )
}

When I move mouse pointer over the image and scroll mousewheel, event.target is set to <img> and event.currentTarget is set to <div>. I can also get the mouse position relative to event.target (event.nativeEvent.offsetX/Y), but that doesn't help me because I don't know the position of <img> relative to <div>.

In other words, I'm stuck... How do I get the mouse position relative to the element that has a handler attached?

like image 320
johndodo Avatar asked Jan 22 '18 19:01

johndodo


1 Answers

I have found a solution which works and am posting it here if it helps someone. I'm not sure though if it is the best one, so I would appreciate some comments (and possibly better solutions).

handleWheel(event) {
  let currentTargetRect = event.currentTarget.getBoundingClientRect();
  const event_offsetX = event.pageX - currentTargetRect.left,
        event_offsetY = event.pageY - currentTargetRect.top;
  //...
}
like image 51
johndodo Avatar answered Sep 28 '22 17:09

johndodo