javascriptjquerycsscss-grid

How to get the grid coordinates of an element using JavaScript?


Let's say I have a 3-column CSS-Grid. Is there a way, using JavaScript, to get the grid-row and grid-column of an auto-placed element?

Example:

console.log($('#test').css('grid-row'), $('#test').css('grid-column'));
// expected output: 2 3 
// actual output: two empty strings
.grid {
  display: grid;
  grid-template-columns: repeat( 3, 1fr);
}
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div id="test"></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Here is a JSFiddle of the example: https://jsfiddle.net/w4u87d2f/7/

In this example I could figure it out by counting the elements and knowing the grid has three columns:

grid-column = $('#test').index() % 3 + 1;
grid-row = Math.ceil( $('#test').index() / 3 )

But that only works for very simple grids and also means I have to consider breakpoints that change the number of columns.

Edit: This is not a duplicate of Retrieve the position (X,Y) of an HTML element, as I'm not interested in pixel coordinates but the row and column number within the CSS-Grid.


Solution

  • //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 } ;
    }