Table of Contents
JavaScript Get Cursor Position refers to the process of identifying the exact location or coordinates of your mouse cursor within a web page. When an event such as a mouse click occurs within your page, we have to track the position where the event was triggered.
JavaScript provides two inbuilt properties to get the X coordinate and Y coordinate, which mean the horizontal and vertical locations of any particular event raised by the user. It’s so important to know these properties while we are trying to create interactive web applications specially try to get mouse position JavaScript.
These two properties are:
- event.clientX Property
- event.clientY Property
Use event.clientX Property to Get Cursor X (Horizontal) Position
The clientX read-only property of the MouseEvent interface is used to find out the value of the X axis or the horizontal position within the viewport at which the event occurred. It’s important to know that clientX always returns 0 while clicking on the top left of your page, regardless of whether the page is scrolled horizontally.
Syntax
Following is the syntax to get the horizontal location of the cursor –
function func_name(event){
var Xlocation=event.clientX;
}
The event.clientX method always return a double floating point value.
Code Example – Get current cursor X position
<!DOCTYPE html>
<html>
<!-- Set the border and click within the border to check the following code -->
<body onclick="displayXPosition(event)" style="min-height: 500px; border:solid 1px black; padding:10px;">
<h3>Get the cursor X Position with JavaScript</h3>
<div id="contentDiv">Click your mouse to see it's X position anywhere on the screen using "event.clientX" property.</div>
<div id="showResult"></div>
<script>
function displayXPosition(event) {
//Get cursor X position
let X = event.clientX;
let resultDiv = document.getElementById("showResult");
resultDiv.innerHTML = "<b>X-coordinate= </b>" + X;
}
</script>
</body>
</html>
Output – Javascript get Cursor Position
Code Explanation
We define a body with a 500px height and a 1px black border to define an area to click. Add a callback function named displayXPosition to write the cursor’s X position. Bind this function to the mouse-click event.
Within the function, we declared a variable named X to hold a double floating point value returned by the event.clientX property. This means the X variable now holds the X axis value of the click position.
Now we need to print the cursor’s X position. To print the horizontal coordinate value of the click event, we set the innerHTML property of the showResult Div to the value of the cursor X axis.
Use event.clientY Property to Get Cursor Y (Vertical) Position
This read-only property of the MouseEvent interface is used to get the position of the cursor in the vertical direction or on the Y-coordinates where the user mouse clicked. Similar to the event.clientX property, it returns a numeric value that contains the cursor Y-axis or Y-coordinate position.
Also note that position is calculated based on viewport; whatever position you come across through the scroll is not a matter at all. Keep it in your mind tightly to master the “JavaScript Get Cursor Position” effectively.
Syntax
Following is the syntax to get the cursor vertical location –
function func_name(event){
var Ylocation=event.clientY;
}
Code Example – Get Current Cursor Y Position
<!DOCTYPE html>
<html>
<!-- Set the border and click within the border to check the following code -->
<body onclick="displayYPosition(event)" style="min-height: 500px; border:solid 1px black; padding:10px;">
<h3>Get the cursor Y Position with JavaScript</h3>
<div id="contentDiv">Click your mouse to see it's Y postion anywhere on the screen using "event.clientY" property.</div>
<div id="showResult"></div>
<script>
function displayYPosition(event) {
// Get cursor Y position
// event.clientY will return a numeric value considering the viewport
let Y = event.clientY;
let resultDiv = document.getElementById("showResult");
resultDiv.innerHTML = "<b>Y-coordinate= </b>" + Y;
}
</script>
</body>
</html>
Output
Code Explanation: Get Mouse Position JavaScript
We are considering the same example as mentioned for event.clientX property of JS. We define a body with a 500px height and a 1px black border to define an area to click. Add a callback function named displayYPosition to write the cursor’s Y position. Bind this function to the mouse-click event as well.
Within the displayYPosition function, we declared a variable named Y to hold a double floating point value returned by the event.clientY property. This means the Y variable now holds the Y axis or Y coordinate value of the mouse click position.
Now we need to print the cursor’s Y position. To print the vertical coordinate value of the mouse-click event, we set the innerHTML property of the showResult Div to the value of the cursor Y axis.
Now combine both the event.clientX and event.clientY read-only JS properties to get the current cursor position. To do that, we are considering the same previous example and modifying these lines of JavaScript code slightly to accommodate both X and Y coordinates together.
Code Example – JavaScript Get Cursor Position on mouseClick Event
<!DOCTYPE html>
<html>
<!-- Set the border and click within the border to check the mouse click postition -->
<body onclick="displayPosition(event)" style="min-height: 500px; border:solid 1px black; padding:10px;">
<h3>Get the cursor Position with JavaScript</h3>
<div id="contentDiv">Click your mouse to see it's postion anywhere on the screen using "event.clientX" and "event.clientY" property.</div>
<div id="showResult"></div>
<script>
function displayPosition(event) {
// Get cursor position
// Both event.clientX and event.clientY will return a numeric value considering the viewport not on the scrolled position
// JavaScript Get Cursor Position
// or get mouse position javascript
let X = event.clientX;
let Y = event.clientY;
let resultDiv = document.getElementById("showResult");
resultDiv.innerHTML = "<b>Cursor Position X Axis= </b>" + X;
resultDiv.innerHTML += "<br /><b>Cursor Position Y Axis= </b>" + Y;
}
</script>
</body>
</html>
Output – JavaScript get Cursor Position
Code Explanation
As we are considering a same example thus these line of code is self-explanatory now.
So far we have discussed about how to get cursor position on mouse click event. You can use the same technique for other JavaScript events also. Some of them are going to mention so that you can master the “JavaScript Get Cursor Position” concept.
Code Example: Using onmousemove JS Cursor Event
<!DOCTYPE html>
<html>
<!-- Set the border and move your mouse within the border to check the mouse postition during move -->
<body onmousemove ="displayPosition(event)" style="min-height: 500px; border:solid 1px black; padding:10px;">
<h3>Get the cursor Position with JavaScript</h3>
<div id="contentDiv">Move your mouse to see it's postion anywhere on the screen using "event.clientX" and "event.clientY" property.</div>
<div id="showResult"></div>
<script>
function displayPosition(event) {
// Get cursor position on mouse move event
// Both event.clientX and event.clientY will return a numeric value considering the viewport not on the scrolled position
// JavaScript Get Cursor Position
// get mouse position javascript
let X = event.clientX;
let Y = event.clientY;
let resultDiv = document.getElementById("showResult");
resultDiv.innerHTML = "<b>Cursor Position of X Axis= </b>" + X;
resultDiv.innerHTML += "<br /><b>Cursor Position of Y Axis= </b>" + Y;
}
</script>
</body>
</html>
Output
Apart from clientX and clientY, you can use pageX, pageY, screenX, and screenY to get the cursor position in JavaScript. But you have to keep in mind the differences between them.
The following table demonstrates the complete differences among JS pageX, pageY, client, client, screen, and screen. Follow the best JS properties accordingly based on your requirements to master “JavaScript Get Cursor Position”:
pageX and pageY | clientX and clientY | screenX and screenY |
---|---|---|
pageX and pageY return the cursor coordinates relative to the fully rendered page of the browser in CSS pixels. | clientX and clientY return the cursor coordinates relative to the viewport in CSS pixels. | screenX and screenY return the cursor coordinates relative to the screen in device pixels. |
The cursor point position and coordinates will change if the user moves the scrollbar within the browser. | The cursor point position or coordinates are always fixed, even if the user moves the scrollbar within the browser. | The cursor point position or coordinates are always fixed, even if the user moves the scrollbar within the browser. |
It means you will get the cursor position, including parts hidden by scrolling. | It means you will get the cursor position, which is considered a visible part of the page. | It means you will get the cursor position, which is considered a visible part of the page. |
You can achieve the same value for clientX or Y by using another JS document property document.documentElement.scrollLeft and document.documentElement.scrollTop. Subtract scrollLeft from pageX and scrollTop from pageY. | You can achieve the same value for pageX and Y by using another JS document property document.documentElement.scrollLeft and document.documentElement.scrollTop. Add scrollLeft with clientX and scrollTop with clientY. | Same as clientX and Y. |
More Useful Tips to Get Cursor Position Accurately
So far, we have discussed the topic “JavaScript Get Cursor Position” using three different JavaScript properties along with detailed code examples. Now is the is the time to master the concepts.
Mastering JavaScript get cursor position quickly and efficiently means understanding and applying various techniques and best practices. Here are ten useful tips for your consideration:
- Attach events like mouseclick, mousemove, and mousedown to the required elements only (not to the document or body) to avoid unnecessary callbacks.
- Use pageX and pageY to get the cursor coordinates relative to the fully rendered page, irrespective of the viewport.
- Client and Screen X or Y properties always return same value.
- Use throttling to limit callbacks; it will improve performance dramatically.
- Use the offset calculation when you need the cursor position relative to another element.
- Ensure compatibility across different browsers.
- Use the ‘dragover’ event during drag operations if the cursor goes outside your expected area.
- Use different types of cursor styles, such as wait, help, zoom-in, and crosshair, to improve cursor interactions.
- Use debounce for performance.
- Use the console.log and debugging tools of your browser to check cursor positions accuracy.
Conclusion
We hope that we have discussed a lot about “JavaScript Get Cursor Position”. As a recap, we can mention that you can use all three JS properties (page X/Y, client X/Y, and screen X/Y) to get the mouse position in JavaScript.
Discussed the concerns of JS getting the mouse position deeply. We also provided 10 most useful tips to master JavaScript for getting cursor position fast!
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply