Search code examples
javascripthtmlmouseeventmousewheelmouse-position

Is it possible to get the mouse position only relative to your element


I have trouble to get the mouse position relative to the elements attached event if i have multiple children in given element.

domElement.addEventListener('wheel', event => {
 event.offsetX //x relative to target element
 event.offsetY //y relative to target element
}

If my mouse hovers a child element it gives the childs position. I am aware of event.pageX or event.clientX but it gives me the mouse position relative to the window/viewport.

const element = document.getElementById("wrapper");
const output = document.getElementById("output");
element.addEventListener("wheel", event =>{
output.innerHTML = `offsetX: ${event.offsetX}, offsetY: ${event.offsetY}`;
});
#wrapper{
  height:300px;
  width:500px;
  background:#ccc;
  position:absolute;
  left:400px;
  top:20px;
}

#child{
  position:relative;
  height:120px;
  width:130px;
  left:50px;
  top:120px;
  background: green;
}
<div id="wrapper">
  <div id="child">
  </div>
</div>

<div id="output"></div>


Solution

  • You can use this: https://developer.mozilla.org/es/docs/Web/API/Element/getBoundingClientRect To get the position of the element, and then it's a simple operation.