How to read mouse's cursor position

Some js applications require to know the position of the mouse's cursor when an event is occured (onclick, onmove, etc), over a html element. That two coordinates of the position, x and y are calculate as a difference between mouses' position related to body's client area and the position of the left and top sides of element's box to respect the same reference.

The mouse's cursor position with espect the element's coordinate system is give by the properties event.clientX and event.clientY associated to the desired event (see here details).

The position of the html element to respect the body area is give by the getBoundingClientRect() method of the element object. The object returned, let name it "bcr" has between other, the members "left" and "top".

The required coordinates has expresions:

x = event.clientX - bcr.left;
y = event.clientY - bcr.top;
event.clientX event.clientY bcr.left bcr.top

A function to read x and y can be write like:

function getXY(ev,elem){
   var bcr = elem.getBoundingClientRect();
   return [ev.clientX-bcr['left'],ev.clientY-bcr['top']];
};

Demo 1

This demo show you an application associated to "mousemove" event. The coordinates are used to display their values.

x:    #  y:    #

0

50

100

150

200

250

0

50

100

150

200


Demo 2

[coming soon]

waalogo