My goal is to generate a 2dgrid with dimensions xMax = 10, yMax = 6
that looks like the following:
x 0 1 2 3 4 5 6 7 8 9
_ _ _ _ _ _ _ _ _ _ y
|_|_|_|_|_|_|_|_|_|_| 0
|_|_|_|_|_|_|_|_|_|_| 1
|_|_|_|_|_|_|_|_|_|_| 2
|_|_|_|_|_|_|_|_|_|_| 3
|_|_|_|_|_|_|_|_|_|_| 4
|_|_|_|_|_|_|_|_|_|_| 5
My aim is to determine on each mouse click which field
(with no actual HTML elements) has been clicked.
I want to obtain the x&y position
of the field from the grid (x, y).
Note: I do not wish to include any additional html-elements and handle their click event; I prefer to calculate the outcome.
To clarify, I have created this code snippet to visualize the starting and ending coordinates:
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: How can I retrieve the coordinates without adding any HTML "fields"?
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 believe utilizing the modulo operator might be the solution, but I am unsure how to implement it in the code.