Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the role of clientX Mouse Event in JavaScript?
The clientX property returns the horizontal (x-axis) coordinate of the mouse pointer relative to the current viewport when a mouse event occurs. Unlike other coordinate properties, clientX is measured from the left edge of the browser's visible area, not including scrollbars.
Syntax
event.clientX
Return Value
Returns a number representing the horizontal pixel position of the mouse pointer relative to the viewport's left edge.
Example: Getting Mouse Coordinates on Click
<!DOCTYPE html>
<html>
<head>
<title>clientX Mouse Event</title>
</head>
<body>
<p onclick="coordsFunc(event)" style="padding: 20px; background-color: #f0f0f0; cursor: pointer;">
Click anywhere on this paragraph to get the x (horizontal) and y (vertical) coordinates
relative to the current window viewport.
</p>
<p id="output"></p>
<script>
function coordsFunc(event) {
var x_coord = event.clientX;
var y_coord = event.clientY;
var xycoords = "X coords: " + x_coord + "px, Y coords: " + y_coord + "px";
document.getElementById("output").innerHTML = xycoords;
}
</script>
</body>
</html>
Example: Mouse Tracking with Multiple Events
<!DOCTYPE html>
<html>
<head>
<title>Mouse Tracking</title>
</head>
<body>
<div id="trackingArea" style="width: 300px; height: 200px; background-color: #e0e0e0; border: 2px solid #ccc;">
Move your mouse over this area
</div>
<p id="coordinates">Mouse coordinates will appear here</p>
<script>
document.getElementById("trackingArea").addEventListener("mousemove", function(event) {
var x = event.clientX;
var y = event.clientY;
document.getElementById("coordinates").innerHTML =
"Mouse position - X: " + x + "px, Y: " + y + "px";
});
</script>
</body>
</html>
Comparison with Other Coordinate Properties
| Property | Reference Point | Description |
|---|---|---|
clientX |
Viewport | Horizontal position relative to visible browser window |
screenX |
Screen | Horizontal position relative to entire screen |
offsetX |
Target Element | Horizontal position relative to the clicked element |
pageX |
Document | Horizontal position relative to entire document (includes scroll) |
Key Points
-
clientXcoordinates remain consistent regardless of page scrolling - Values are always relative to the current viewport's left edge
- Commonly used for positioning elements like tooltips or context menus
- Works with all mouse events: click, mouseover, mousedown, etc.
Conclusion
The clientX property is essential for getting accurate mouse position relative to the viewport. It's particularly useful for creating interactive elements that need to respond to mouse position within the visible browser area.
Advertisements
