JSFiddle - React, Tailwind, and code Playground
by Ben
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Table Example</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
td {
border: 1px solid #ddd;
border-radius: 5px;
}
</style>
</head>
<body>
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Banana</td>
<td>Pineapple</td>
</tr>
<tr>
<td>Carrot</td>
<td>Broccoli</td>
<td>Cucumber</td>
<td>Tomato</td>
</tr>
<tr>
<td>Elephant</td>
<td>Giraffe</td>
<td>Lion</td>
<td>Tiger</td>
</tr>
<tr>
<td>Red</td>
<td>Green</td>
<td>Blue</td>
<td>Purple</td>
</tr>
</table>
</body>
</html>
JavaScript
// Select all table cells
const cells = document.querySelectorAll('td');
// Initialize current cell index
let currentCell = 0;
// Add event listener for keydown events
document.addEventListener('keydown', (event) => {
// Move current cell index based on arrow key pressed
switch (event.keyCode) {
case 37: // Left arrow
currentCell = (currentCell - 1) % cells.length;
break;
case 38: // Up arrow
currentCell = (currentCell - 4 + cells.length) % cells.length;
break;
case 39: // Right arrow
currentCell = (currentCell + 1) % cells.length;
break;
case 40: // Down arrow
currentCell = (currentCell + 4) % cells.length;
break;
default:
return;
}
// Remove focus from previously selected cell
cells[currentCell === 0 ? cells.length - 1 : currentCell - 1].blur();
// Highlight contents of cell with focus
cells.forEach((cell) => {
if (cell === cells[currentCell]) {
cell.style.backgroundColor = '#ffffcc';
// Allow cell to be edited and select cell contents
cell.contentEditable = true;
const range = document.createRange();
range.selectNodeContents(cell);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
//cell.fovus();
//cell.select();
} else {
cell.style.backgroundColor = '';
// Disable editing of other cells
cell.contentEditable = false;
}
// Add focus to newly selected cell
cells[currentCell].focus();
//cells[currentCell].select();
});
});