How to get the grid coordinates of an element using JavaScript?
//Add click event for any child div of div = grid
$(document).ready(function(){
$('.grid').on('click', 'div', function(e){
GetGridElementsPosition($(this).index()); //Pass in the index of the clicked div
//Relevant to its siblings, in other words if this is the 5th div in the div = grid
});
});
function GetGridElementsPosition(index){
//Get the css attribute grid-template-columns from the css of class grid
//split on whitespace and get the length, this will give you how many columns
const colCount = $('.grid').css('grid-template-columns').split(' ').length;
const rowPosition = Math.floor(index / colCount);
const colPosition = index % colCount;
//Return an object with properties row and column
return { row: rowPosition, column: colPosition } ;
}
The above answer is a great start, and uses jQuery. Here is a pure Javascript equivalent, and also implements an "offset" in case you have specified the first child element's grid column (such as in a calendar where you specify the first day of the month)
function getGridElementsPosition(index) {
const gridEl = document.getElementById("grid");
// our indexes are zero-based but gridColumns are 1-based, so subtract 1
let offset = Number(window.getComputedStyle(gridEl.children[0]).gridColumnStart) - 1;
// if we haven't specified the first child's grid column, then there is no offset
if (isNaN(offset)) {
offset = 0;
}
const colCount = window.getComputedStyle(gridEl).gridTemplateColumns.split(" ").length;
const rowPosition = Math.floor((index + offset) / colCount);
const colPosition = (index + offset) % colCount;
//Return an object with properties row and column
return { row: rowPosition, column: colPosition };
}
function getNodeIndex(elm) {
var c = elm.parentNode.children,
i = 0;
for (; i < c.length; i++) if (c[i] == elm) return i;
}
function addClickEventsToGridItems() {
let gridItems = document.getElementsByClassName("grid-item");
for (let i = 0; i < gridItems.length; i++) {
gridItems[i].onclick = (e) => {
let position = getGridElementsPosition(getNodeIndex(e.target));
console.log(`Node position is row ${position.row}, column ${position.column}`);
};
}
}
addClickEventsToGridItems();
Here is a corresponding Pen that shows it in action on a calendar with a specified offset.