Davis Johnson
Davis Johnson

Reputation: 99

Find live mouse coordinates inside the container

So i was dabbling around JavaScript coordinates and created a container in which the x and y coordinates of the mouse are to be displayed inside a container.

The code works almost fine except the fact that it shows the coordinates only when i enter the container and doesn't change unless i reenter the container. here is the code below:-

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>king crimson</title>
</head>
 
<body>
  <style>
    body{
      display: flex;
      align-items: center;
      align-content: center;
    }
    .container{
      width: 500px;
      height: 400px;
      background-color: crimson;
      margin: auto;
      color: white;
      padding-top: 2rem;
      text-align: center;
    }
  </style>
<div class="container"></div>

<!-- START JAVASCRIPT -->

  <script>
    const box = document.querySelector('.container');
    
    box.addEventListener('mouseover', e =>{
      let x = event.clientX;
      let y = event.clientY;
      const coords = `
      Coordinate of x is ${x} and coordinate of y is ${y}
      `

      box.innerHTML = coords;
    });
  </script>

<!-- END JAVASCRIPT-->
</body>

</html>

Upvotes: 0

Views: 194

Answers (1)

Yanjan. Kaf.
Yanjan. Kaf.

Reputation: 1725

  const box = document.querySelector('.container');
    
    box.addEventListener('mousemove', e =>{
      let x = event.clientX;
      let y = event.clientY;
      const coords = `
      Coordinate of x is ${x} and coordinate of y is ${y}
      `;

      box.innerHTML = coords;
    });
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>king crimson</title>
</head>
 
<body>
  <style>
    body{
      display: flex;
      align-items: center;
      align-content: center;
    }
    .container{
      width: 500px;
      height: 400px;
      background-color: crimson;
      margin: auto;
      color: white;
      padding-top: 2rem;
      text-align: center;
    }
  </style>
<div class="container"></div>




<!-- END JAVASCRIPT-->
</body>

</html>

Upvotes: 1

Related Questions