Is there a way to detect which CSS grid column and row an element is in using javascript?
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>
How to find in which column a CSS grid layout element is placed using JavaScript
What I have done here is loop through all elements, and every time the left position increases and is less than my elements position, I increase a counter to keep track of the column.
I've also modified snippet here to make a little bit more interactive. If you click the div's it re-selects and shows new column number..
var myElement = document.querySelector('div:nth-child(5)');const allElements = document.querySelector('.grid').querySelectorAll('div');
//myElement.style.background = '#f00';myElement.classList.add('item-found');
function showFound() { let maxcolpos = -1, colposCount = 0; for(elem of allElements) { let l = elem.getBoundingClientRect().left; if (l > maxcolpos) { maxcolpos = l; if (myElement.getBoundingClientRect().left > l) colposCount ++; } }
const columnIndex = colposCount + 1; //zero based, leave +1 if you want 0 based myElement.innerText = 'Column = ' + columnIndex; } showFound(); document.querySelector('.grid').addEventListener("click", function(e) { if (e.target && !e.target.matches(".grid")) { myElement.classList.remove('item-found'); myElement.innerText = ''; myElement = e.target; myElement.classList.add('item-found'); showFound(); } });
.grid { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 30px;}
.item,.item-large { padding: 30px; background: #3cf;}
.item-large { grid-row: span 2;}
.item-found { background-color: red;}
<div class="grid"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item-large"></div> <div class="item"></div> <div class="item-large"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div></div>
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 } ;
}
Using Javascript with CSS Grid
In CSS change your set Attribute from class to id
item.setAttribute("id", "grid-item");
Because in css when you use # it's mean ID but when you use . its mean Class
Ref : https://www.w3schools.com/cssref/css_selectors.asp
How to target a specific column or row in CSS Grid Layout?
Not possible with CSS.
CSS targets HTML elements, attributes and attribute values.
Grid columns and rows have none of these "hooks".
You'll have to target the grid items directly.
You wrote:
For example, say I have a 3 row by 2 column CSS Grid Layout:
grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;
. How would I select all elements from the 2nd column?
grid-container { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; grid-gap: 10px; padding: 10px; height: 50vh; background-color: gray;}
grid-item { background-color: lightgreen;}
grid-item:nth-child(2n) { border: 2px dashed red;}
<grid-container> <grid-item></grid-item> <grid-item></grid-item> <grid-item></grid-item> <grid-item></grid-item> <grid-item></grid-item> <grid-item></grid-item></grid-container>
How can I get an array of values or rows from my grid layout?
You can grab all the items using querySelectorAll
and use getComputedStyle
to count the number of columns in each row. see this answer
var computedStyle = getComputedStyle(document.querySelector('.grid-table'))
var columnsCount = computedStyle.getPropertyValue("grid-template-columns").split(" ").length // in our case 5
var container = document.querySelector('.grid-table')
var columns = getComputedStyle(container).getPropertyValue("grid-template-columns").split(" ").length;
var items = document.querySelectorAll('.grid-table div');
var output = []
var row = 0;
items.forEach(function (item, i) {
if (i % columns === 0) {
if (output.length > 0) {
row++ ;
}
output.push([])
}
output[row].push(item.innerHTML)
});
console.log(output)
.grid-table {
display: grid;
grid-template-columns: repeat(5, 1fr);
}
<div class="grid-table">
<div>head1</div>
<div>head2</div>
<div>head3</div>
<div>head4</div>
<div>head5</div>
<div>item1</div>
<div>item2</div>
<div>item3</div>
<div>item4</div>
<div>item5</div>
<div>item6</div>
<div>item7</div>
<div>item8</div>
<div>item9</div>
</div>
Related Topics
JavaScript Style.Display="None" or Jquery .Hide() Is More Efficient
JavaScript Image Overlay Over a Specified Div
Adding Custom CSS and Js to Shopify
Isotope Jquery Plugin Doesn't Show Properly on Chrome
Calculate Absolute Dimensions of a Div Rotated in Perspective with CSS3
Using Jquery How to Show and Hide Different Div's Onclick Event
Transitioning Affixed Navigation Bar - CSS
Handling JavaScript Events in Wkwebview
Retain Cursor Position in Contenteditable
How to Change <Body> Tag Style from Child Component
How to Reasonably Animate Font Awesome Lock Icons
Detect Support for Background-Attachment: Fixed
Why Do Developers Append a Query String in JavaScript Files' Stylesheet Links
Youtube API Not Working with iPad/Iphone/Non-Flash Device
Jquery Example (In Jsfiddle) Working in Firefox But Not in IE8, 7