Home > database >  Get Coordinates of image on click
Get Coordinates of image on click

Time:05-09

I have a set of divs which are dynamic, I somehow want them in a different order. So I'm using flex order to control the order of the divs. One of the div contains an image. By clicking on that image it should console the x & y coordinates of the click which is related to the image. I have made everything I want. But the problem is I'm getting the y coordinates in a negative number, I believe it is because of the order I have changed using flex.

Here's what I tried

The expected result: When I click on the border image top left position it should console the exact position of the click which is related to the image.

CodePudding user response:

This is caused by your own calculations. You can simplify the calculation using this function

GetMousePositionRelativeToTarget(e) {
    // Get the target
    const target = e.target;

    // Get the bounding rectangle of target
    const rect = target.getBoundingClientRect();

    // Mouse position
   const x = e.clientX - rect.left;
   const y = e.clientY - rect.top;

   console.log(x   ':'   y);
   return [x, y];
}    
  • Related