How to get current position of the mouse in JavaScript


In this short tutorial, we will learn how to get the current mouse cursor position with Javascript. sss2hh While developing a website, we sometimes want to add some animation to our HTML elements based on the movement of our mouse.

So to add such animation we have to first get the current position of the mouse cursor on the webpage. We can get that by adding an event handler to the mouse action.

Let's see how we can do it.

Getting the current X and Y coordinates of the mouse cursor using event handler.

To get the current X and Y coordinate of the mouse cursor we have to attach an event handler to the mouse event. We will use mousemove event to console log the X and Y coordinates of the cursor.

Let's see an example of the mousemove event.

document.addEventListener('mousemove', (event) => {
   console.log(`X: ${event.clientX}, Y: ${event.clientY}`) 
}); 

The addEventListener() adds an event listener to the document and the function runs whenever the event occurs.

When the event occurs, it passes an event object to the function as the first parament.

The event object allows us to access the client X and client Y coordinates and log them to the console.

Now, whenever you move the mouse, you can see the coordinates in your console

Demo:

 <body>
    <div class="main-wrapper">
      <h1>
        Get position of cursor using Javascript
      </h1>
    </div>
    <script>
      const main = document.querySelector(".main-wrapper");
      main.addEventListener("mousemove", (event) => {
        console.log(`X: ${event.clientX}, Y: ${event.clientY}`);
      });
    </script>
  </body>

Edit gracious-poitras-jh1yqm


💾 Recommended Articles