JSFiddle - React, Tailwind, and code Playground
HTML
<form id="pieceSelection">
Number of Rows<input type="text" id="numOfPieces" size="1" maxLength="1" value="3"/><br>
<input type="submit" value="Scramble image" />
</form>
CSS
/* CSS for index.html */
body
{
background:gray;
color:white ;
}
/* Center the grid */
#grid
{
margin-left:auto;
margin-right:auto;
border: 1px white solid ;
}
/* Center Form */
#pieceSelection
{
text-align:center;
}
/*Highlight selected cell*/
JavaScript
// Event handler for clicking table cells
$('body').on('click', '#grid td', function(e) {
var empty = $("#blankCell").get(0);
if (!empty || this == empty) return; // abort, abort!
var currow = this.parentNode,
emptyrow = empty.parentNode;
var cx = this.cellIndex,
cy = currow.rowIndex,
ex = empty.cellIndex,
ey = emptyrow.rowIndex;
if (cx == ex && Math.abs(cy - ey) == 1 || cy == ey && Math.abs(cx - ex) == 1) {
// empty and this are next to each other in the grid
var afterempty = empty.nextSibling,
afterthis = this.nextSibling;
currow.insertBefore(empty, afterthis);
emptyrow.insertBefore(this, afterempty);
}
});
// listener attached to form submit button
// generates table
$('#pieceSelection').submit(function(e) {
e.preventDefault();
var $tbl = $('<table border="1">').attr('id', 'grid');
var $tbody = $('<tbody>').attr('id', 'tableBody');
var rowCount = $("#numOfPieces").val();
var tileCount = 0;
for (var i = 0; i < rowCount; i++) {
var trow = $("<tr>").attr('id', 'row' + i); // New row
for (var j = 0; j < rowCount; j++) {
var $cell = $("<td>").text('Row : ' + i + ', Col: ' + j);
tileCount++;
$cell.appendTo(trow);
}
trow.appendTo($tbody);
}
$tbl.append($tbody);
$('table').remove();
$('body').append($tbl);
// set table cell to be blank for logic purposes
$('#grid tr:nth-child(2) td:last').prev().text("empty");
$('#grid tr:nth-child(2) td:last').prev().attr('id', 'blankCell');
return false;
});