Obtain the position of the click

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.

Answer №1

To find the pseudo-coordinates, follow this method:

const calculateCoordinates = function(event) {
  let rows = 6,
      cols = 10,
      fieldWidth = 40,
      fieldHeight = 40,
      paddingLeft = 60,
      paddingTop = 80,
      clickedX = event.clientX,
      clickedY = event.clientY;

   const x = Math.floor((clickedX - paddingLeft) / fieldWidth);
   const y = Math.floor((clickedY - paddingTop) / fieldHeight);
   console.log("Clicked Coordinates:", x, y)
}

$(window).click(function(e) {
  calculateCoordinates(e)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Below is an example with demo elements displayed:

let rows = 6,
  cols = 10,
  fieldWidth = 40,
  fieldHeight = 40,
  paddingLeft = 60,
  paddingTop = 80;

for (let y = 0; y < rows; y++) {
  for (let x = 0; x < cols; 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)
  }
}
let calculateCoordinates = function(event) {
  clickedX = event.clientX,
    clickedY = event.clientY;

  const x = Math.floor((clickedX - paddingLeft) / fieldWidth);
  const y = Math.floor((clickedY - paddingTop) / fieldHeight);
  console.log("Clicked Coordinates:", x, y)
}

$(window).click(function(e) {
  calculateCoordinates(e)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to achieve a curved outer edge for a rectangle using CSS?

I am trying to style the header and footer of my website, which is built using a SAAS CMS. Unfortunately, I am unable to change the HTML structure, but I can add custom CSS. My goal is to create curved headers and footers with upward and downward curves. I ...

The Fuel-ui module in Angular 2 fails to function properly when loaded from a different directory

We recently switched from ng-cli to Gulp for building our Angular2 project, and we are utilizing Fuel-ui. An unusual error has come up. We have incorporated Fuel-ui's alert component into one of our components. When referencing fuel-ui from node_mo ...

Challenges with PHP jQuery AJAX

I'm facing a jQuery AJAX problem. The issue arises when I call a page through AJAX, it loads correctly but one character - the apostrophe - gets replaced by I don't know why this is happening? Expected output: "of course it’s based on the" C ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

Dynamic dropdown menu that includes client-side filtering functionality

Does anyone know of an ajax control that meets the following criteria: Enables users to type in for auto-suggestions Dropdown only displays values starting with the characters typed One postback is needed to fetch all data on initial key-in, then f ...

Prevent Symfony2 Twig from rendering HTML content

Is there a way to disable the rendering of HTML responses in Twig? I am currently working on a RESTful API and my goal is to completely prevent HTML rendering. For instance, if I access /foo/bar without an oAuth Access Token, Symfony2 should reply with a ...

Maintaining the Readability of Promise Chains

Creating promise chains with arrays is a method I've become accustomed to. It's quite simple to follow along a chain of promises when each one fits neatly on its own line like so: myArray.map(x => convertX) .filter() .whatever() .etc() ...

Angular ng-repeat encounters difficulty in parsing Arabic object

As I create a JSON object that contains Arabic content shown below $scope.arabicContent = ["ردهة","قاعة الاجتماعات","مبرمجين الجوال","المدراء","المحاسبة","المحاسبة","المبرمجين‎","مطبخ‎ ...

Is there a way to share the Username and Password without the need to manually input it?

My goal is to develop a C++ application for my classmates at school. Currently, they are required to visit our school's website and navigate to the login page. Once there, they enter their username and password, log in, and proceed to find their spec ...

Ensuring a smooth user experience on Internet Explorer with CSS backup

I am looking to incorporate a CSS 3D effect into a website. I have successfully implemented it on all browsers except Internet Explorer (including IE 11). As far as I know, IE does not support preserve-3d. Can someone help me add a fallback option for IE, ...

Utilize D3 to Rotate Text within an SVG in Circular Motion, Following by Self-rotation

In my visualization, the labels are arranged around the center of a circle by rotation. However, this results in the labels on the left side of the circle appearing upside down. Is there a way to rotate the labels on the left side independently after the i ...

Tips for saving a webcam captured image location into a MySQL database

I've been experiencing issues with the code I used to capture an image. While the image is successfully stored in the specified folder, I'm unable to store the image path in the database. The code stops executing after displaying the "Uploading.. ...

Having trouble loading the socket.io.js file in electron

I am in the process of developing a chat application using Node.js, Electron, and Socket.io. However, I am encountering an issue when trying to load /socket.io/socket.io.js. Every time I attempt to do so, I receive the following error: Failed to load res ...

Is it possible to simultaneously execute an animate and a fade out effect?

Is there a way to simultaneously move "app1" to the left and fade it out? Currently, the functions are executing one after the other. I want them to occur simultaneously, without the left movement happening before the fade out. Thank you! <!DOCTYPE h ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Basic AngularJS framework with minimal external dependencies

I have been searching for an AngularJS skeleton to set up my project, but it seems like all the skeletons I find online require the installation of numerous dependencies through npm and/or bower. Due to security concerns at the firm where I am working on ...

Use jQuery to collapse all of the child elements that are currently expanded under a specific parent element

In my list order, I have multiple levels nested within each other: <ul> <li>level 1 a <ul> <li>level 2 a <ul> <li>level 3 a</li> < ...

How can jQuery and cheerio be used to select links that contain a specific word in either the href attribute or text content?

Looking for a method in jQuery to efficiently identify and select all links that contain a specific keyword within either the href attribute or the link text itself. Any suggestions on how to achieve this using Cheerio for Node.js? I am currently working ...

Reactjs is failing to display the page

I am facing an issue where the components are not rendering in the browser even though there is no error being displayed. This makes it difficult to troubleshoot and resolve the problem. Can someone help me identify the root cause? import React, { Com ...

Encountering an issue with setting up Firefox profile in protractor when using selenium webdriver configuration

var p = require("p"); var ChromeProfile = require("chrome-profile"); var createChromeProfile = function(settingsMap) { var deferred = p.defer(); var chromeProfile = new ChromeProfile(); for (var k in settingsMap) { chromeProfile.setSe ...