JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div class="container">
<div class="wrapper-board">
</div>
<div class="output-wrapper">
<span class="output-value"></span>
</div>
</div>
</body>
CSS
/*Board in Javascript*/
.wrapper-board {
width: 220px;
font-size: 0;
height: 200px;
margin: 50px auto 0 auto;
}
.wrapper-board > i {
width: 20px;
height: 20px;
background: #900;
border: 1px solid #009;
display: inline-block;
cursor: pointer;
}
.wrapper-board > i:hover {
background: #090;
}
.output-wrapper {
padding-top: 20px;
text-align: center;
}
.output-value {
font-size: 16px;
font-weight: bold;
}
JavaScript
var chooseCellWrap = document.querySelector('.wrapper-board'),
outputValue = document.querySelector('.output-value'),
widthSegments = 10,
heightSegments = 10,
i,
getCellIndex = function(DOMNode) {
return parseInt(DOMNode.getAttribute('data-index'));
},
getCellByIndex = function(index) {
return document.querySelector('i[data-index="' + index + '"]');
},
getSurroundingIndices = function(index) {
var arr = [];
arr.push(index - 1); // left
arr.push(index + 1); // right
arr.push(index - widthSegments); // top
arr.push(index + widthSegments); // bottom
arr.push(arr[2] - 1); // top left
arr.push(arr[2] + 1); // top right
arr.push(arr[3] - 1); // bottom left
arr.push(arr[3] + 1); // bottom right
return arr;
};
// create board
for (i = 0; i < widthSegments * heightSegments; i++) {
var chooseCellElem = document.createElement('i');
chooseCellElem.setAttribute('data-index', i);
chooseCellElem.setAttribute('data-posx', i % widthSegments);
chooseCellElem.setAttribute('data-posy', Math.floor(i / widthSegments));
chooseCellWrap.appendChild(chooseCellElem);
}
document.addEventListener('click', function(e) {
var index,
neighbours,
neighbour,
x, y, i;
x = parseInt(e.target.getAttribute('data-posx'));
y = parseInt(e.target.getAttribute('data-posy'));
if (e.target.hasAttribute('data-index')) {
index = getCellIndex(e.target);
neighbours = getSurroundingIndices(index);
if (x === 0) {
neighbours[0] = -1; // exclude left
neighbours[4] = -1; // exclude top left
neighbours[6] = -1; // exclude bottom left
}
if (x === widthSegments - 1) {
neighbours[1] = -1; // exclude right
neighbours[5] = -1; // exclude top right
neighbours[7] = -1; // exclude bottom right
}
for (i = 0; i < neighbours.length; i++) {
neighbour =...