2

I wish you a healthy day. I had one question. As you can see in the photo below, console.log contains the coordinates of the mouse on the photo. How can I write these coordinates as X, Y under the photo so that they will change instantly in the same way and appear on the page, not the console? At the same time, when clicked with the mouse, I want it to write the coordinates under it as a list, like a record. Thanks.

I am using these codes to write the coordinates on console.log :

    let pos = getCursor()
    console.log('pos:', pos)

The Screenshot of the screen and console : Screenshot

  • Do you want to write coordinates to some element below the image? – s.kuznetsov May 30 '21 at 08:19
  • Are you looking for this? https://developer.chrome.com/blog/new-in-devtools-70/#watch – pavi2410 May 30 '21 at 08:37
  • Yes I wanna write the coordinates to below the image. The coordinates should be coordinates of the image not the browser's or screen's mouse locations. – Nurettin Önder May 30 '21 at 08:42
  • Does this answer your question? [Convert console.log to output to a div](https://stackoverflow.com/questions/39488552/convert-console-log-to-output-to-a-div) – freedomn-m May 30 '21 at 09:28

1 Answers1

0

https://htmldom.dev/calculate-the-mouse-position-relative-to-an-element/

Code:

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <img
      src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiuNnCTe_G0nD5EnKG62TETP_bkdDfmn4BKg&usqp=CAU"
      alt=""
    />
    <script src="index.js"></script>
    <p id="display-pos"></p>
    <p id="display-pos-save"></p>
  </body>
</html>


JS

addEventListener("mousedown", function (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;

  document.getElementById(
    "display-pos-save"
  ).innerHTML = `pos x = ${x} pos y = ${y}`;
});

addEventListener("mousemove", function (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;

  document.getElementById(
    "display-pos"
  ).innerHTML = `pos x = ${x} pos y = ${y}`;
});