I have been working on creating a catalog for a website that showcases different items in a grid layout. Currently, I have implemented a function that allows users to hide specific items by clicking an image. However, when an item is hidden, the remaining visible items do not automatically reposition themselves within the grid.
For example, if I initially have 6 items spread over 2 rows and 3 columns as follows:
1 2 3
4 5 6
And then proceed to hide numbers divisible by 2, the grid will look like this:
1 3
5
Is there a way to make the grid rearrange itself like this instead?
1 3 5
In my current implementation, I am using display = 'none' to hide the items.
Below is a simplified version of the code I am working with:
var ChangeLayout = function(rarity) {
var listItemContainers = document.getElementsByClassName("itemContainer");
var listItemContainersByRarity = document.getElementsByClassName(rarity);
var j;
var h;
if (rarity == 'all') {
for (j = 0; j < listItemContainers.length; j++) {
document.getElementsByClassName("itemContainer")[j].style.display = 'block';
}
} else {
for (j = 0; j < listItemContainers.length; j++) {
document.getElementsByClassName("itemContainer")[j].style.display = 'none';
}
for (h = 0; h < listItemContainersByRarity.length; h++) {
document.getElementsByClassName(rarity)[h].style.display = 'block';
}
}
}
#catalogGrid {
display: grid;
grid-auto-flow: row;
grid-template-columns: repeat(3, 1fr);
grid-column-gap: 5px;
grid-row-gap: 5px;
}
<img id="gemStoneAll" onclick="ChangeLayout('all')" />
<img id="gemStoneUncommon" onclick="ChangeLayout('uncommon')" />
<img id="gemStoneRare" onclick="ChangeLayout('rare')" />
<img id="gemStoneVeryRare" onclick="ChangeLayout('veryrare')" />
<ul id=catalogGrid>
<li>
<div class="itemContainer rare">
</div>
</li>
<li>
<div class="itemContainer veryrare">
</div>
</li>
<li>
<div class="itemContainer uncommon">
</div>
</li>
<li>
<div class="itemContainer uncommon">
</div>
</li>
<li>
<div class="itemContainer rare">
</div>
</li>
<li>
<div class="itemContainer rare">
</div>
</li>
</ul>