How to Track Mouse Position in JavaScript?
In JavaScript, two properties, “clientX” and “clientY”, are utilized for tracking a mouse position in the visible area of the browser. Both properties are executed in a specified area provided by the user.
The syntax of the “clientX” and “clientY” properties is provided below:
Syntax of clientX
The “clientX” returns the horizontal axis of the mouse pointer.
Syntax of clientY
Similarly, the “clientY” property returns the vertical axis with the movement of the mouse pointer.
Example
The example explains the usage of tracking mouse position in JavaScript.
HTML Code
<style>#div1 { height: 200px; width:100%;
border: 1px solid #444;
}</style>
<div id="div1" onmousemove="getCursorPosition(event)">
</div>
<div>X Mouse position: <span id="c_p_x"></span>.
</div>
<div>Y Mouse position: <span id="c_p_y"></span>.
</div>
<script src="test.js"></script>
The explanation of the code is as follows:
- Firstly, the div tag is created and a “div1” id is assigned to it.
- Different properties, including height, width, border, and position, are applied within <style> tag.
- After that, the getCursorPosition() method is utilized by passing an “event”.
- After that, the “X Mouse position” and “Y Mouse position” are extracted with the cursor movement.
- In the end, the source path of the JavaScript file is assigned “test.js” within <script> tag.
The code for the “test.js” file is provided below:
JavaScript Code
document.getElementById("c_p_x").textContent = event.clientX;
document.getElementById("c_p_y").textContent = event.clientY;
}
In this code:
- Firstly, the getCursorPosition() method is called and an argument is passed named “event”.
- After that, the document.getElementById is utilized to extract the HTML elements whose ids are “c_p_x” and “c_p_y”.
- The event.clientX returns the horizontal coordinate based on the client area and the “event.clientY” is employed by returning the vertical coordinate in the browser.
Output
The output shows that “X Mouse position” and “Y Mouse position” are tracked by changing the mouse position in the browser.
Conclusion
In JavaScript, the “clientX” and “clientY” properties track the mouse position. These properties can be combined with a user-defined function to get the coordinates of the mouse position. This post has demonstrated the method to track mouse position in JavaScript using the “clientX” and “clientY” properties. The example practiced here shows that the x-coordinate and y-coordinate are dynamically updated whenever a mouse moves.