Search code examples
javascripthtmljquerygrid

How to find the index of a grid item before and after being dragged in javascript


I am making a chess game with HTML, CSS and JS but i cannot figure out how to get the index of a piece in the grid before and after being dragged(i also use jquery and jquery-ui)

This is an image of the "game":

https://i.sstatic.net/w3qmG.png

CODE HTML

<div class="chessboard ">
  <div class="cell white">
    <img class="piece" id="rook" draggable="true" src="assets/pieces/black/rook.png" alt="">
  </div>
  <div class="cell black">
    <img class="piece" id="knight" draggable="true" src="assets/pieces/black/knight.png" alt="">
  </div>

  ..............................................

  <div class="cell black">
    <img class="piece" id="knight" draggable="true" src="assets/pieces/white/knight.png" alt="">
  </div>
  <div class="cell white">
    <img class="piece" id="rook" draggable="true" src="assets/pieces/white/rook.png" alt="">
  </div>
</div>

CODE JS

const pieces = document.querySelectorAll(".piece");
const grid = document.querySelector(".chessboard");
var grid_layout = []

// i tried to find at least the starting position by clicking on the pieces
pieces.forEach((piece) => {
  piece.addEventListener("click", () => {
    console.log($(piece.id).index())
  })
})

This is one of my failed attempts

function GetElementIndex() {
  if ($('.piece').hasClass("ui-draggable-dragging")) {
    console.log(GetGridElementsPosition($('.piece').index()));
  }
}

This function returns the position of an element, given the index(which i am looking for), fortunately this one works quite well

function GetGridElementsPosition(index) {
  const colCount = $(".chessboard")
    .css("grid-template-columns")
    .split(" ").length;
  const rowPosition = Math.floor(index / colCount) + 1;
  const colPosition = (index % colCount) + 1;
  return { row: rowPosition, column: colPosition };
}

Below is the function that enables the pieces to be dragged

$(function () {
  $(".piece").draggable({
    start: function () {
      console.log("Starting Index:");
      GetElementIndex();
    },
    stop: function () {
      console.log("Ending Index:");
      GetElementIndex();
    },
    grid: [100, 100],
    activeClass: "dragging",
  });
});

EDIT

So due to some help from the comments i managed to get what i needed. I gave every cell of the grid an x and y value (like {1, 1} or {5, 8}) and i rendered the pieces through js and not html. I then found their current position by doing this:

var col = Math.ceil($(this).position().left / 100);
var row = Math.ceil($(this).position().top / 100);

This is just the piece being dragged(inside function in draggable())


Solution

  • The easiest way maybe to add at the html generation a position to the cells with data-x and data-yas custom html attributes? https://www.w3schools.com/tags/att_global_data.asp