const plural = (singular, plural) =>
(number) =>
`${number} ${number === 1 ? singular : plural}`;
const ranges = plural("range", "ranges");
document.querySelector(".hover").addEventListener("mouseenter", function() {
// Save selection
console.log(`Saving selection...`);
const selection = window.getSelection();
const savedRanges = [];
for (let i = 0; i < selection.rangeCount; ++i) {
savedRanges.push(selection.getRangeAt(i));
}
// Remove it and report
selection.removeAllRanges();
console.log(`${ranges(savedRanges.length)} saved and removed.`);
// Restore it after a moment
setTimeout(() => {
console.log(`Restoring ${ranges(savedRanges.length)}...`);
const selection = window.getSelection();
selection.removeAllRanges();
// To support unusual Firefox behavior around a mix of selections
// inside and outside tables, restore ranges whose start container
// is TR first, then others
for (const range of savedRanges.filter(({startContainer: {nodeName}}) => nodeName === "TR")) {
selection.addRange(range);
}
for (const range of savedRanges.filter(({startContainer: {nodeName}}) => nodeName !== "TR")) {
selection.addRange(range);
}
console.log(`Done`);
}, 800);
});
.hover {
display: inline-block;
border: 1px solid black;
padding: 4px;
}
<p>
Select text in the document, then move your mouse over the <strong>Hover to Run</strong> box below but <strong>don't</strong> click it (because that would remove your selection). The action will happen when your mouse enters the <strong>Hover to Run</strong> area. On Firefox, try doing multiple selections by holding down Ctrl when selecting, or by Ctrl-clicking table cells.
</p>
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>One</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
<tr>
<td>five</td>
<td>six</td>
</tr>
</tbody>
</table>
<div class="hover">Hover to Run</div>