1

i want to get position of mouse pointer than the a box

for example :

 !

I need this space but if the mouse enters the red or yellow box i get another number.

i know we have e.offsetY but this give the position than e.target so if the box have a child this dont work

i know too we have e.layerY but this give the position than relative so if the child element have relative position style ot transform its not work true

for example :

const parent = document.querySelector(".parent");
const result = document.querySelector(".result");


parent.addEventListener("mousemove",(e)=>{
result.innerText = `offsetY: ${e.offsetY} , layerY: ${e.layerY}`})
.parent{
width:200px;
height:200px;
background-color:blue;
padding:30px;
position:rlative
}

.result{
background-color:#999;
color:black;
padding:10px;
margin:20px;
}


.child-red{

background-color:red;
width:30px;
height:30px;

}


.child-yellow{
background-color:yellow;
width:30px;
height:30px;
margin-top:30px;
position:relative
<div class="parent">

  <div class="child-red">
  
  </div>
  
  
   <div class="child-yellow">
  
  </div>

</div>


<p class="result">offsetY: 0 , layerY: 0</p>
pilchard
  • 12,414
  • 5
  • 11
  • 23
Alireza
  • 35
  • 4
  • 1
    Does this answer your question? [Javascript: Get mouse position relative to parent element](https://stackoverflow.com/questions/2614461/javascript-get-mouse-position-relative-to-parent-element) – pilchard Dec 31 '21 at 10:52
  • Try using `e.y` – aerial Dec 31 '21 at 11:40

1 Answers1

0

offsetY as it says in the name gives you the offset of the cursor inside of an element, If you want the cursor co-ordinates in px values with respect to the document.body you need event.cursorY