JanMod
JanMod

Reputation: 446

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>

Upvotes: 0

Views: 502

Answers (3)

JanMod
JanMod

Reputation: 446

I found a solution which i do not really like. The function getBoundingClientRect ().

const element = document.getElementById("wrapper");
const output = document.getElementById("output");
element.addEventListener("wheel", event =>{
   let { x, y } = element.getBoundingClientRect();
   let position = { x, y };
   let mousex = event.clientX - position.x;
   let mousey = event.clientY - position.y;
output.innerHTML = `offsetX: ${mousex}, offsetY: ${mousey}`;
});
#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>

Upvotes: 0

Luis Gurmendez
Luis Gurmendez

Reputation: 664

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.

Upvotes: 1

santamanno
santamanno

Reputation: 636

Welcome to Stack Overflow!

If you set this CSS attribute to your child element:

pointer-events: none;

The wheel position will always be relative to the parent, but remember it will disable all mouse interactions with the child element.

You can find more info here: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Upvotes: 0

Related Questions