I'm building a web app with pure JavaScript. I'd like the user to be able to select an entire paragraph when they tap it once in Chrome Android, and have the "Copy" Android context menu pop up so they can easily copy the text they just selected.
I've already got the entire paragraph being selected on one tap, no problem, using the Selection API. But, the "Copy" menu doesn't come up when the text is selected. Why not, and how can I get it to show up in Chrome on Android?
I've made a JSFiddle isolating my problem which you can open on Chrome Android to check out. Here's the code from it.
HTML:
<p>Lorem ipsum</p>
<p>Dolorum est</p>
JavaScript:
let selectedNode = undefined;
document.querySelectorAll("p").forEach(function (element) {
element.addEventListener("click", function () {
const selection = window.getSelection();
selection.removeAllRanges();
if (element === selectedNode) {
selectedNode = undefined;
} else {
const range = document.createRange();
range.selectNodeContents(element);
selection.addRange(range);
selectedNode = element;
}
})
});
When I tap either of the paragraphs, the paragraph text is selected, but no Copy dialog comes up:
When I tap the paragraph again to DESELECT it (which essentially calls window.getSelection().removeAllRanges(), see the JavaScript above), THEN the Copy dialog comes up:
I'm curious why this happens, but ultimately I'd like to know:
How can I get the Copy dialog to show up when the text is selected, rather than when it's deselected?