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?
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;
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With