Can someone tell me the method to retrieve the coordinates of a click using jQuery?

I have a div with an 8x8 grid and I am looking to practice using jQuery. How can I determine which row and column a specific div was clicked on? I attempted to use event.pageX and event.pageY, but these only provide the click coordinates rather than the specific row and column.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="script.js"></script>
    <title></title>
</head>
<body>

    <div id="gameArea"></div>

</body>
</html>

There is also a CSS file included:

body {
    margin: 0;
    padding: 20px;
}

.tile {
    position: absolute;
    background-color: rgb(115, 255, 50);
    cursor: pointer;
}

.tile:hover {
    background-color: darkgreen;
}

.disabled {
    background-color: black;
    border:1px solid black;
}

.enabled{
    background-color: white;
    border: 1px solid white;

}

#gameArea {
    background-color: black;
    position: relative;
    padding: 0px;
    border: 2px solid black;

}

Below is the JavaScript code in my JS file:

const max_clicks = 3;

const table_sz = 8;
const tile_sz = 88;
const border_w = 4;
const margin_w = 2;


let game_area;


function createTile(row, col){

    let tile;

    if ((row + col) % 2 === 0){

        tile = $('<div class = "tile disabled"></div>');
    }
    else{

        tile = $('<div class = "tile enabled"></div>');

        tile.attr('clicks', 0);
    }

    tile.css("margin", margin_w.toString() + "px");
    tile.css("border-width", border_w.toString() + "px");

    tile.attr('row', row);
    tile.attr('col', col);

    tile.css( {

        top: row * (tile_sz + 2 * (border_w + margin_w) ),
        left: col * (tile_sz + 2 * (border_w + margin_w) ),
        height: tile_sz,
        width: tile_sz,
    } );

    return tile;
}

function createTable(){

    for (let row = 0; row < table_sz; ++row){

        for (let col = 0; col < table_sz; ++col) {

            let tile = createTile(row, col);

            game_area.append(tile);
        }
    }
}

function createGameArea(){

    game_area = $('#gameArea');

    game_area.css( {

        height: 800,
        width: 800
    } );
}




function selectTileAt(position){

    return $(".tile[row=" + position[0].toString() + "][col=" + position[1].toString() + "]");
}



$(document).ready(function(){

    createGameArea();

    createTable();

} );

Answer №1

If you want to include custom data attributes like row and column, it's recommended to use the standard syntax data-*. This is considered the proper way to add custom attributes to elements. Here's an example:

tile.attr("data-row", row);
tile.attr("data-col", col);

Next, within the loop that generates the table, you can assign a click event listener for each tile using jQuery's on event handler function. Within this listener, you can retrieve the row and column of the clicked tile:

tile.on("click", function (evt) {
  console.log('Clicked row: ', $(evt.target).attr("data-row"));
  console.log('Clicked column: ', $(evt.target).attr("data-col"));
});

const max_clicks = 3;
const table_sz = 8;
const tile_sz = 88;
const border_w = 4;
const margin_w = 2;

let game_area;

function createTile(row, col) {
  let tile;

  if ((row + col) % 2 === 0) {
    tile = $('<div class = "tile disabled"></div>');
  } else {
    tile = $('<div class = "tile enabled"></div>');

    tile.attr("data-clicks", 0);
  }

  tile.css("margin", margin_w.toString() + "px");
  tile.css("border-width", border_w.toString() + "px");

  tile.attr("data-row", row);
  tile.attr("data-col", col);

  tile.css({
    top: row * (tile_sz + 2 * (border_w + margin_w)),
    left: col * (tile_sz + 2 * (border_w + margin_w)),
    height: tile_sz,
    width: tile_sz,
  });

  return tile;
}

function createTable() {
  for (let row = 0; row < table_sz; ++row) {
    for (let col = 0; col < table_sz; ++col) {
      let tile = createTile(row, col);

      tile.on("click", function (evt) {
        console.log("Clicked row: ", $(evt.target).attr("data-row"));
        console.log("Clicked column: ", $(evt.target).attr("data-col"));
      });

      game_area.append(tile);
    }
  }
}

function createGameArea() {
  game_area = $("#gameArea");

  game_area.css({
    height: 800,
    width: 800,
  });
}

$(document).ready(function () {
  createGameArea();
  createTable();
});
body {
  margin: 0;
  padding: 20px;
}

.tile {
  position: absolute;
  background-color: rgb(115, 255, 50);
  cursor: pointer;
}

.tile:hover {
  background-color: darkgreen;
}

.disabled {
  background-color: black;
  border: 1px solid black;
}

.enabled {
  background-color: white;
  border: 1px solid white;
}

#gameArea {
  background-color: black;
  position: relative;
  padding: 0px;
  border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="gameArea"></div>

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

The <div> element is not displaying the JSON response when using Ajax

I have created a basic login form and I am attempting to validate it using an AJAX call. The validation process is successful, but the issue arises when the correct email or password is entered. Instead of displaying the JSON success or error message in a ...

Utilize information stored in a database to automatically navigate to a different webpage

I am currently working with PHP, HTML, and a mySQL database. Here are my current project requirements: Retreive specific data from the database and output it. Compare this data with predetermined values. If the data falls outside of the specified range, ...

Dynamically insert a disabled option in ng-options

I'm struggling to create a division in my select/option dropdown menu. The dropdown structure I am aiming for is as follows: NO IMAGE CUSTOM IMAGE rest of data.... Despite my efforts, the code doesn't seem to be working as expected. Can ...

Invoke a MVC function from a web page using JavaScript

Currently, I am working with an ASP.NET MVC application and have the following Ajax call on one of the pages: $.ajax({ url: "/Home/GetAuthCode/", type: "GET", contentType: 'application/json', success: function () ...

The interconnectivity between ngAfterViewInit in Angular's LifeCycle and observables

enable.service.ts @Injectable({ providedIn: 'root' }) export class EnableService { isEnabled$ = from(this.client.init()).pipe( switchMap(() => this.client.getEnabled()), map(([enabled, isAdmin]) => ({enabled: true, isAdmin: fals ...

I am incorporating a fulfilment code to create a shopping cart for the order bot, but unfortunately, I am receiving an undefined

Within the function provided, the content of the item and its quantity in the order are printed. function confirmitem(agent){ const item = agent.getContext('item'), Food = item.parameters.Food, quantity = item.parameters ...

What is the method to establish a stopping condition for an interval in Angular 8 that activates once a certain condition is met?

I am looking to stop API calls when a variable becomes undefined. ngOnInit() { // Set interval to update data continuously const source = interval(3000); if(this.groupId){ this.subscription = source.subscribe( val => this. ...

The navigation bar spans the entire width of my webpage

I came across this cool man code at and I'm trying to make the menu bar stretch across the entire width of my page. The theme I'm using is called nvidia. You can download the original code by getting the zip file from the link above. Here&apos ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

Using Scrapy to extract data from Project Euler's website

Currently, I am working on scraping projecteuler.net using Python's scrapy library as a way to practice my skills. While there are existing implementations of similar scrapers online, they seem too complex for my needs. I simply want to save the probl ...

Transforming a blogspot template into a standalone webpage

Is it possible to take a blogspot template and convert it into its own HTML CSS website? I have the main HTML page and CSS, but when I upload it to my server, much of the styling is missing. For example, I would like to use the layout from , but I do not ...

Input Form Label inexplicably rounded off at odd location

I've been utilizing Bootstrap to style my page, and I used the input form classes provided by Bootstrap to create this input field. However, upon loading the page, I noticed some strange rounding occurring between the label and the input space. http ...

What is the best way to create a Bootstrap table with a fixed header that stays in place

I am currently working on creating a Bootstrap table that is responsive. My goal is to have the table head scroll along with the table data when scrolling down, without setting a fixed height for the table. I want the page to expand naturally as more rows ...

How can you prevent <div>s from overlapping when using the float property?

I am facing a CSS challenge that I haven't been able to resolve yet: My goal is to create a webpage layout with two divs side-by-side in a row (using float:left; and float:right;) and then a third div below them. The issue arises when the top row (de ...

Displaying a document file on a webpage hosted by a raspberry pi

My Raspberry Pi hosts a local website that does not require an internet connection. I want the webpage to display text from a large file line by line as users access it. For example, if the text file contains: Hello How are You doing Today? The brow ...

Combining React Material UI with an endless scrolling component to dynamically load table data

I need some help with using react infinite scroll within a react material table. I attempted to implement it but the scrolling affected the entire page instead of just the table body. I want the headers to remain sticky while only the table body should h ...

Experiencing issues with a blank or non-functional DataGrid in Material UI components

My DataGrid table is showing blank. I experienced the same problem in a previous project and recreated it in a new one with updated versions of django and mui libraries. Here is an example of my data displayed with DataGrid not working I posted a bug rep ...

Checking the status of an Xmlhttp request when the URL is inaccessible, all without the use of libraries

I am currently working on testing the functionality of a given URL using Ajax. In order to achieve this, I made some modifications to the Ajax code. function checkURLStatus() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Ch ...

Need to get an item from a collection at the library?

Is it possible to import and use an object from a library? For instance, suppose we have a file named data.js with the following content: return { "name": "Testing" } In the file index.js, could we do something like this: const data = require('. ...