Reputation: 2530
I'm doing a memory game using plain js and css-grid. I have seen solution with flex-box, but I want to do it with css-grid instead. The challenge I faced now is placing the grid elements into the grid container using javascript. I know how to do it in css but couldn't do it with js. I have tried the following so far with no luck:
const fillGrid = () => {
let i = 1;
document.getElementsByClassName('grid-item').forEach(element => {
element.style.gridArea = `block${i++}`;
document.getElementById('grid').appendChild(element);
});
}
fillGrid();
My intention was to assign 'grid-area' properties for each grid-item in javascript while keeping the remaining properties of the css-grid in the css part. I wanted to use javascript because I want to change the position of each element dynamically.
HTML:
<div class="grid-container" id="grid">
<div class="grid-item">
<img src="img/2.jpg" class="frot-face"/>
</div>
<div class="grid-item">
<img src="img/1.jpg" class="frot-face"/>
</div>
<div class="grid-item">
<img src="img/3.jpg" class="frot-face"/>
</div>
<div class="grid-item">
<img src="img/5.jpg" class="frot-face"/>
</div>
<div class="grid-item">
<img src="img/6.jpg" class="frot-face"/>
</div>
<div class="grid-item">
<img src="img/7.jpg" class="frot-face"/>
</div>
<div class="grid-item">
<img src="img/8.jpg" class="frot-face"/>
</div>
<div class="grid-item">
<img src="img/9.jpg" class="frot-face"/>
</div>
</div>
CSS:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr 1fr;
grid-template-areas: 'block1 block2 block3 block4' 'block5 block6 block7 block8' 'block1 block2 block3 block4' 'block5 block6 block7 block8';
padding: 3em 2em 3em 2em;
grid-gap: 1em;
width: 73vmin;
margin: auto;
border-radius: 10px;
}
Upvotes: 1
Views: 2521
Reputation: 2530
I have been able to solve this issue. The main reason my code was not working was because I misused gridArea
property. Unlike the CSS grid-area
property, in JS( or DOM) this property is not used to assign names to grid items. Instead it's
used as a shorthand property for the grid-row-start, grid-column-start, grid-row-end and the grid-column-end properties
Reference: https://www.w3schools.com/cssref/pr_grid-area.asp or https://www.w3docs.com/learn-css/grid-area.html. My final code looks like:
const fillGrid = () => {
let col = 1, row = 1;
const items = [...document.getElementsByClassName('grid-item')];
const grid = document.getElementById('grid');
items.forEach(item => {
item.style.gridArea = `${row} / ${col}`;
col++;
if(col>4){
col=1;
row++;
}
});
}
fillGrid();
CSS:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
padding: 3em 2em 3em 2em;
grid-gap: 1em;
width: 73vmin;
margin: auto;
border-radius: 10px;
border: 2px solid black;
}
img{
width: 100px;
height: 100px;
}
Upvotes: 1