I'd like to create a 2dgrid with lets say xMax = 10, yMax = 6
to get something like this:
x 0 1 2 3 4 5 6 7 8 9
_ _ _ _ _ _ _ _ _ _ y
|_|_|_|_|_|_|_|_|_|_| 0
|_|_|_|_|_|_|_|_|_|_| 1
|_|_|_|_|_|_|_|_|_|_| 2
|_|_|_|_|_|_|_|_|_|_| 3
|_|_|_|_|_|_|_|_|_|_| 4
|_|_|_|_|_|_|_|_|_|_| 5
Now I'd like to calculate on every mouse click in which of the fields
(I will not add any real HTML-elements) I have clicked.
As result I'd like to get the x&y position
of the field from the grid (x, y).
Note: I do not want to add html-elements and listen for their click event, I'd like to calculate the result.
To make it a bit cleared I created this snippet to visualize where the coordinates start and end:
let sizeY = 6,
sizeX = 10,
fieldWidth = 40,
fieldHeight = 40,
paddingLeft = 60,
paddingTop = 80;
for (let y=0; y<sizeY; y++) {
for (let x=0; x<sizeX; x++) {
let posX = x*fieldWidth + paddingLeft,
posY = y*fieldHeight + paddingTop
$(`<div class="field"></div>`).css({
top: posY,
left: posX,
width: fieldWidth,
height: fieldHeight,
position: "absolute",
background: `rgb(${parseInt(Math.random()*255)},
${parseInt(Math.random()*255)},
${parseInt(Math.random()*255)})`
}).appendTo(document.body)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My question: Without adding any HTML "fields", how do I get the coordinates?:
let calculateField = function(event) {
let sizeY = 6,
sizeX = 10,
fieldWidth = 40,
fieldHeight = 40,
paddingLeft = 60,
paddingTop = 80,
clickedX = event.clientX,
clickedY = event.clientY;
// ?
console.log(clickedX, clickedY)
}
$(window).click(function(e) {
calculateField(e)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: I'm pretty sure this is a task for the modulo operator but tbh I got no clue how to implement the code.