JSFiddle - React, Tailwind, and code Playground
HTML
<table id="table" tabindex="0">
<tbody>
<tr>
<td>R1C1</td>
<td>R1C2</td>
</tr>
<tr>
<td>R2C1</td>
<td>R2C2</td>
</tr>
<tr>
<td>R3C1</td>
<td>R3C2</td>
</tr>
</tbody>
</table>
CSS
table, td {
border: 1px solid #ccc;
border-collapse: collapse;
padding: 2px;
outline: none;
}
.selected::selection {
outline: none;
background: transparent;
}
JavaScript
window.onload = function () {
var selectedCell,
table = document.getElementById('table'),
selectCell = function (e) {
var target = e.target,
range, selection;
if (target.tagName.toLowerCase() !== 'td') {
while (target = target.parentElement) {
if (target.tagName.toLowerCase() === 'td') {
break;
}
}
}
if (!target || target.tagName.toLowerCase() !== 'td') {
return;
}
if (selectedCell) {
selectedCell.style.backgroundColor = '';
}
target.style.backgroundColor = '#ff0';
selectedCell = target;
},
beforeCopyCell = function (e) {
var range, selection;
if (!selectedCell) {
return;
}
if (e.type === 'keydown' && (!e.ctrlKey || e.which !== 67)) {
return;
}
if (e.type === 'mousedown' && e.which !== 3) {
return;
}
selectedCell.classList.toggle('selected');
selection = window.getSelection();
selection.removeAllRanges();
range = document.createRange();
range.selectNode(selectedCell);
selection.addRange(range);
},
afterKeyCopyCell = function (e) {
if (!selectedCell) {
return;
}
if (e.type === 'keyup' && (!e.ctrlKey || e.which !== 67)) {
return;
}
selectedCell.classList.toggle('selected');
selection = window.getSelection();
selection.removeAllRanges();
},
afterMouseCopyCell = function (e) {
if (!selectedCell) {
return;
}
...