EN
JavaScript - get mouse position
0 points
In this article, we would like to show you how to get mouse X and Y positions using JavaScript.
Quick solution:
xxxxxxxxxx
1
var element = document.querySelector('#element-id');
2
3
element.addEventListener('click', function(event) {
4
console.log(`x: ${event.clientX}, y: ${event.clientY}`);
5
});
Note:
The coordinates are measured from the upper left corner (
0
,0
).
In this example, we use event.clientX
and event.clientY
properties to get mouse position.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
body {
6
height: 100px;
7
padding: 10px;
8
border: 1px solid #28a745;
9
border-radius: 10px;
10
}
11
</style>
12
</head>
13
<body>
14
<div>Click here to get mouse coordinates.</div>
15
<script>
16
17
document.body.addEventListener('click', function(event) {
18
console.log(`x: ${event.clientX}, y: ${event.clientY}`);
19
});
20
21
</script>
22
</body>
23
</html>