Obtain the index when clicked using jquery

I am currently working on creating a 2 player checkers game for my college project. However, I have hit a roadblock in determining the index of the 2D array when I click on a game piece.

The HTML code structure I have divided into:

  • table - representing the game board
  • row - each row corresponds to the height of the array
  • cell - each cell represents a game piece and the width of the array

To initialize the game, I have set a default array as follows:

  var board = [
    [0, 1, 0, 1, 0, 1, 0, 1],
    [1, 0, 1, 0, 1, 0, 1, 0],
    [0, 1, 0, 1, 0, 1, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [2, 0, 2, 0, 2, 0, 2, 0],
    [0, 2, 0, 2, 0, 2, 0, 2],
    [2, 0, 2, 0, 2, 0, 2, 0],
  ];

Where: - 0 represents an empty cell - 1 represents Player 1's pieces - 2 represents Player 2's pieces

For determining the position, I am using the following code:

function getPosition() {
  $('.row').on('click', function() {
    console.log( $('.row').index(this) );
  });
  $('.cell').on('click', function() {
    console.log( $('.cell').index(this) );
  });
}

While I am able to successfully obtain the row index between 0 and 7, for the cell within the row, I am getting indices ranging from 0 to 63. This is causing confusion for the subsequent comparisons and game logic implementation.

You can view the code on CodePen at the following link: http://codepen.io/michaelthompson/pen/jVdrav

Answer №1

Whenever you encounter this situation, you can effortlessly utilize $(this).index() to retrieve the index among the element's sibling elements.

Since every row click also involves clicking a cell, you can simplify the process by combining them like so:

$('.cell').on('click', function() {
   var $cell = $(this),  
       columnIndex = $cell.index(),
       rowIndex = $cell.parent().index();
});

The function $('.cell').index(this) operates by encompassing the entire class collection on the page, hence the output of 0 to 63.

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

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

Utilizing JodaTime with JavaScript (AngularJS): A Comprehensive Guide

I am utilizing DateTime to create Date objects and sending them as JSON to the UI. How can I work with this in JavaScript (specifically AngularJS) and convert it back and forth? For instance, if I need the user to update the time, I should be able to retr ...

What is the best way to incorporate an external .css file into my Angular project by referencing its URL?

I'm managing a collection of CSS files online and I need to incorporate each one into my project based on its specific requirements. One component in particular is connected to different numerical IDs in the router. I am looking for a way to dynamica ...

Testing React components using the React Testing Library

I've been working on creating a test unit for my React Application using React Testing Library, but I've hit a roadblock. I've gone through all the documentation but I'm still stuck. The API was set up using create React app. One of th ...

Modifying data within nested objects using Typescript

Imagine having an object like this: { b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" }, ​ pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" } } with the in ...

Difficulty in styling with ag-Grid in SharePoint Framework (SPFX) combined with Angular

I'm currently delving into the world of custom SharePoint Web Parts using SharePoint Framework (SPFX) in combination with Angular Elements. One roadblock I've encountered is that when trying to implement ag-Grid, the style definitions for the gri ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Extracting data from large Arrays in PHP

In my script, I store player data in an array that changes based on the number of players present. The structure of the array is as follows: Array ( [0] => Array ( [Id] => 0 [Name] => Playername1 [Fr ...

A guide on using Sinon to mock a custom $http transform

Exploring the proper method for mocking an http post with a custom transform in Angular using the Sinon mocking framework. In my CoffeeScript Sinon unit test setup, I define mocks like this: beforeEach module(($provide) -> mockHttp = {} $provide.value ...

Using React hooks to reset state in a reducer: step-by-step guide

event.js import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useHistory } from 'react-router-dom'; import { addEvent } from '../actions/event'; ...

The error message displays "window.addEventListener is not a function", indicating that

Recently, I've been dealing with this code snippet: $(document).ready(function(){ $(window).load(function() { window.addEventListener("hashchange", function() { scrollBy(0, -50);}); var shiftWindow = function() { scrollBy(0, - ...

The styling for material UI's default endAdornment is lacking accuracy

My Autocomplete component from material UI v5 includes a default endAdornment icon. However, the icon appears to have the CSS property top:unset, causing it to be styled incorrectly. Here is the code for rendering the Autocomplete: <Grid item xs={3}> ...

Is there a way to make an HTML link target the same as JavaScript window.opener?

Within my project, the main page is where users log in and access the primary tables. Additionally, there are numerous supplementary pages that open in separate windows. Once the login session times out, it is essential to restrict user access to any cont ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

How can I add a Facebook HTML5 Like Button to AJAX Pages?

I am trying to implement the Facebook HTML5 Like Button on my Ajax views. On my main page, this is what I have: <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById( ...

Having trouble with Javascript/ajax/php: data is successfully sent from server to client, but client to server communication is not working as

Apologies for the duplicate post (Admins, kindly remove the other one!). I've been receiving great assistance from you all and was hoping to seek your help once again with the following question: I am currently working on implementing AJAX by allowin ...

Show a malfunction with the `show_message` function

How can I show the die() message in if($allowed) in the same location as the move_uploaded_file result? <?php $destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'; $allowed[] = 'image/gif'; $allowed[] = ' ...

Accessing the react-bootstrap tab using the history feature in React

Currently, I am in the process of developing a multi-form page that includes login, registration, and lost password functionalities displayed using tabs with react-bootstrap. The technologies I am using for this project are react 17.0.2, react-bootstrap 2 ...

Perform PHP function without refreshing the page when clicking

I have a PHP script that displays an alert box with the options OK or CANCEL. If OK is clicked, it redirects to a link that triggers a PHP function to delete the selected image. <?php //echo $pictures['binId']; if(count($other_images)) { ...

Having trouble establishing a connection between Node.js and SQL Server using Tedious library

When attempting to connect to a local SQL Server instance using Node.js and Tedioius, I encounter the following error: { [ConnectionError: Failed to connect to XXXXX:1433 - connect ECONNREFUSED] name: 'ConnectionError', message: 'Failed ...