Hello. Suppose there is a <div id="block"></div> . How to make sure that the position of the cursor starts its report only inside the block, and only within it. That is, when the cursor is in the upper left corner of this block, the result was X:1, Y:1 .

  • It is necessary, apparently, to subtract the distance between the top of the page and the top border of the div . Also with the left side. - YozhEzhi
  • one
    Thank you for the answer :) - 4oremty

1 answer 1

It is necessary to subtract from the position of the cursor the position of the element. The position of the element is found with the getBoundingClientRect() function:

 var block = document.querySelector('#block'); block.onmousemove = function(event) { var mpos_left = event.pageX, mpos_top = event.pageY var mpos_block_left = mpos_left - this.getBoundingClientRect().left, mpos_block_top = mpos_top - this.getBoundingClientRect().top; this.innerHTML = 'Left: '+mpos_block_left+'; Top: '+mpos_block_top; }; 
 #block { width: 200px; height: 200px; margin: 20px; border: 2px solid #000; } 
 <div id="block"></div>