Aaron Sterling Aaron Sterling - 7 months ago 20
Javascript Question

Save mouse coordinate in an array

I want to get mouse coordinate in an array. Also I click anywhere I can't get mouse coordinate.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<style>body {background-color: ivory;}</style>
</head>
<body>
<p id="results">result</p>
<script>
var x = document.getElementById("body");
var offsetX = x.offsetLeft;
var offsetY = x.offsetTop;
x.addEventListener('click', handleClick, false);
function handleClick(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
document.getElementById("results").innerHTML = "You clicked at: " + mouseX + "/" + mouseY;
}
</script>
</body>
</html>

Answer

There is no element within your HTML that has id="body". You can access the <body> element using document.body.

Also, the body is rather small since it only contains your one <p> element, so you may want to add some css so that you can click anywhere in the window and your event will fire:

html, body {
    height: 100%;
}

To store the calculated coordinates in an array, just create a blank array:

var coords = [];

Then add coordinates to them:

coords.push([mouseX, mouseY]);

Here is a working example:

var x = document.body;
var offsetX = x.offsetLeft;
var offsetY = x.offsetTop;
x.addEventListener('click', handleClick, false);

var coords = [];

function handleClick(e) {
  mouseX = parseInt(e.clientX - offsetX);
  mouseY = parseInt(e.clientY - offsetY);  
  coords.push([mouseX, mouseY]);
  document.getElementById("results").innerHTML = "You have clicked at: " + JSON.stringify(coords);
}
html, body {
  height: 100%;
}
<p id="results">result</p>

Comments