JSFiddle - React, Tailwind, and code Playground

by efortis

HTML

<div id="fieldPerimeter"> </div>

CSS

* {
  margin: 0;
  pading: 0;
  color: white;
}

.box{
  width: 100px;
  height: 50px;
  background-color: #ccc;
  margin: 10px;
  font-size: 2em;
  text-align: center;
  line-height: 1.5em;
  position:absolute;
}

#fieldPerimeter{
  height: 100%;
  background-color: blue;
}

JavaScript

(function () {
  var i, lastBox, lastMove,
    MAX_DIVS       = 72,
    BOX_HEIGHT     = 50,
    BOX_WIDTH      = 100,
    BOX_MARGIN     = 5,
    field          = document.getElementById('fieldPerimeter'),
    fieldHeight    = 500, //field.offsetHeight Hardcoded for jsfiddle
    maxRows        = Math.floor(fieldHeight / (BOX_HEIGHT + BOX_MARGIN)),
    rowIndex       = 0,
    colIndex       = 0,
    lastLeftOffset = 0,
    lastTopOffset  = 0;

  function moveBox(box, where) {
    switch (where) {
    case "north":
      lastTopOffset -= BOX_HEIGHT + BOX_MARGIN;
      box.style.top  = lastTopOffset  + 'px';
      box.style.left = lastLeftOffset + 'px';
      rowIndex -= 1;
      break;

    case "east":
      lastLeftOffset += BOX_WIDTH + BOX_MARGIN;
      box.style.top  = lastTopOffset  + 'px';
      box.style.left = lastLeftOffset + 'px';
      colIndex += 1;
      break;

    case "south":
      lastTopOffset += BOX_HEIGHT + BOX_MARGIN;
      box.style.top  = lastTopOffset  + 'px';
      box.style.left = lastLeftOffset + 'px';
      rowIndex += 1;
      break;

    default:
      break;
    }
  }

  for (i = 0; i < MAX_DIVS; i += 1) {
    lastBox = document.createElement('div');
    lastBox.className = 'box';
    lastBox.innerHTML = i;
    field.appendChild(lastBox);
    if (i === 0) {
      rowIndex += 1;
    } else {
      if (colIndex % 4 === 0 && rowIndex < maxRows) {
        moveBox(lastBox, "south");
        lastMove = "south";
      } else if (colIndex % 2 === 0 && rowIndex !== 1 && lastMove !== "south") {
        moveBox(lastBox, "north");
        lastMove = "north";
      } else {
        moveBox(lastBox, "east");
        lastMove = "east";
      }
    }
  }
}());