JSFiddle - React, Tailwind, and code Playground
by 3rror404
HTML
<div class="pixels"></div>
CSS
.pixels {
display: flex;
flex-wrap: wrap;
width: 1020px;
}
.pixelarea {
box-sizing: border-box;
background: #f2f2f2;
border: 1px solid #e6e6e6;
width: 10px;
height: 10px;
}
.pixelarea:hover {
background: orange;
}
.pixelarea.selected {
background: limegreen;
}
.allowed {
background: lightGreen;
}
JavaScript
/*
* Create pixel grid
*/
const $pixelsContainer = $('.pixels');
const columnCount = 102;
const rowCount = 5;
for (let i = 0; i < (columnCount * rowCount); i++) {
$pixelsContainer.append('<div class="pixelarea" />');
}
/* END Create pixel grid */
let selectedIndex = -1;
$('.pixelarea').on('click', function() {
const clickedIndex = $(this).index();
if (selectedIndex === -1) {
/*
* This is the first selection
*/
selectedIndex = clickedIndex;
$(this).addClass('selected');
markAllowed();
return;
}
if ($(this).hasClass('allowed')) {
selectedIndex = $(this).index();
$(this).addClass('selected');
markAllowed();
}
});
function markAllowed() {
const row = Math.floor(selectedIndex / columnCount) + 1;
// Allow left if we haven't clicked the first element in the row
if (selectedIndex - 1 > 0) {
$('.pixelarea').eq(selectedIndex - 1).addClass('allowed');
}
/*
* Allow right if we haven't clicked the last element in the row
*/
if (((selectedIndex + 1) / row) < columnCount) {
$('.pixelarea').eq(selectedIndex + 1).addClass('allowed');
}
// Allow above if we haven't clicked in the first row
if (row > 1) {
$('.pixelarea').eq(selectedIndex - columnCount).addClass('allowed');
}
// Allow below
$('.pixelarea').eq(selectedIndex + columnCount).addClass('allowed');
}