This is why you should learn CSS Grid

Heres a simple codepen I’m proud of. Maybe when I have more time I’ll add animations!

2 Likes

I like the your style.

How about this to replace the nested for loops?

$ghosts.innerHTML = ghostNames.reduce((html, ghost) => html + `
  <div class="ghost" id="${ghost}">
    ${pixels.reduce((pixHtml, pixel) => pixHtml + `
      <div class="square ${colorMap[pixel]}"></div>`,"")
    }
  </div>
`,"");

or this slightly more readable version using map?

$ghosts.innerHTML= ghostNames.map(ghost => `
  <div class="ghost" id="${ghost}">
    ${pixels.map(pixel => `
      <div class="square ${colorMap[pixel]}"></div>
    `).join('')}
  </div>
`).join('');
1 Like

Thanks @RandellDawson! I could use map or reduce, but I’m thinking that performance would be the same since the higher order functions are also nested. Is there something that I’m missing?

Performance-wise, all of those createElement calls in your nested for loops creates an overall slower result than a single update to one element’s ($ghost) innerHTML property. Based on that, the performance may be equal. If you used nested for loops with the single innerHTML update, there might be a slight performance gain, but probably not because there are only there are not a significant number of elements in the pixels array.

Ahh, that makes a lot of sense. I’ve always felt hesitant to use innerHTML.

If you want to stick with something that creates the elements like createElement does, but want better performance, then you should look into using createDocumentFragment.

I like updating the innerHTML property, because it allows me to use template literals to make the code more readable, when there are multiple nested elements to add to the DOM.

Pretty neat.

Is there a reason why you are not using the repeat function for your grid-template-columns?

grid-template-columns: repeat(14,1fr);

Also, I guess it doesn’t hurt to be explicit about it, but you don’t actually need the grid-template-rows property.

1 Like

I’ll checkout createDocumentFragment. But I agree with you. innerHTML is powerful. I think when it really comes down to it, I’d probably benefit by using less divs for each ghost and utilizing more CSS grid capabilities.

Anyways, I have some decisions to make.

I always forget how powerful CSS is. Thanks for this.

Hey! Great job, man! I like it.

1 Like