CSS Grid Fidget Toy
I started today’s post off trying to find a way to rotate a grid of divs and try to find a way to make some of those divs stand upright within the rotated grid. That was a bit too difficult, and may not possible in the way I was hoping. So I ended up making this. I’m not sure what it is, but I tried using some JavaScript from my lightbox in another way.
View the code:
HTML and JS
<div class="code-block">
<div class="grid">
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
</div>
</div>
<script>
// ---------
// Variables
// ---------
// ---------
// Functions
// ---------
function toggleItem() {
if(this.getAttribute('class') === "grid-item") {
this.setAttribute('class',"grid-item toggled");
} else {
this.setAttribute('class', "grid-item");
}
};
// ---------
// Events
// ---------
let tilesArray = [];
window.onload = function () {
tilesArray = document.getElementsByClassName('grid-item');
for (let i = 0; i < tilesArray.length; i++) {
tilesArray[i].setAttribute('id',`grid-item-${[i]}`);
document.querySelector(`#grid-item-${[i]}`).addEventListener('click', toggleItem);
};
};
</script>
CSS
.code-block {
max-width: 30em;
padding: 1rem;
background-color: #eeeeeeee;
margin: 1rem auto;
border-radius: 1rem;
}
@supports (display: grid) {
.grid {
display: grid;
grid-template-columns: repeat(6, 44px);
grid-template-rows: repeat(6, 44px);
gap: 0;
width: 264px;
margin: 3rem auto;
box-shadow: .25rem .25rem .25rem 0 rgba(0, 0, 0, .125);
}
.grid-item:hover {
background-color: rgb(52, 52, 224);
}
.grid-item {
background-color: rgb(26, 26, 224);
border: solid 1px white;
display: grid;
place-items: center;
width:44px;
height:44px;
transition: background-color .125s ease-out, transform .25s ease-in-out;
cursor: pointer;
}
.toggled {
background-color: white;
transform: translateY(-.25rem);
}
}