Is there a way to detect which CSS grid column and row an element is in using javascript?

by Dylan Cristy   Last Updated May 22, 2020 23:26 PM - source

Is there a way to dynamically detect in javascript which grid column and row an element is in, in a CSS grid?

I have a grid that I set up with three breakpoints so that it either has 4, 3, or 2 columns.

What I want to do is if a user clicks in a cell, dynamically overlay a new element in the cell immediately to the right of the cell that was clicked, except if it's in the right-most column, in which case the overlay element will go in the cell to the left.

I know I can use grid-column and grid-row to specify the cell I want to put the new thing in, but in order to be able to use that, I need to know the column and row of the cell that was clicked.

How can I dynamically determine that?



Answers 1


Here. Bind it to a click, but you can have access to this function any way you like. Click on block to see if it is last columns or not. The function accepts current grid-template-columns so it will work on any breakpoint.

//Add click event for any child div of div = grid
$(document).ready(function() {
  $('.grid').on('click', 'div', function(e) {  
    GetGridElementsPosition($(this).index(), $(this)); //Pass in the index of the clicked div
  });
});

function GetGridElementsPosition(index, element) {

  //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 colPosition = index % colCount;
  const rowPosition = Math.floor(index / colCount);
  
  /* determine if it is a last column */
  if (colPosition==(colCount-1)) {
    $(element).html('row:'+rowPosition+'. col:'+colPosition+'. Last column');
  } else {
    $(element).html('row:'+rowPosition+'. col:'+colPosition+'. Not last column');
  }

}
.grid {
  display: grid;
  grid-template-columns: repeat( 3, 1fr );
  grid-row-gap: 1em;
  grid-column-gap: 1em;
}

.grid div {
  height: 2em;
  background: blue;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

focus.style
focus.style
May 22, 2020 21:59 PM

Related Questions


Each row editable using ui-grid AngularJS

Updated November 29, 2017 07:26 AM

set Cell Style during export to excel in ui-grid

Updated June 17, 2017 10:26 AM


CSS grid layout changing column width with javascript

Updated September 11, 2017 16:26 PM