In iOS Safari, I’m able to select text programmatically using the following code. However, the text selection UI (selection handles and blue overlay) don’t show, unless the user has already manually selected something on the page.
Everything works as expected in other browsers I’ve tested (Android Chrome, macOS Chrome, macOS Safari, and macOS Firefox) – it’s only failing in iOS/iPadOS Safari.
I’ve tried various event listeners to trigger the text selection: onclick, pointerdown, pointerup, touchstart, touchend, etc. – but no luck.
Does anyone know of a workaround or have any ideas?
const paragraphs = document.querySelectorAll('p');
for (paragraph of paragraphs) {
paragraph.addEventListener('click', selectParagraphContents);
}
function selectParagraphContents(event) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(event.currentTarget);
selection.removeAllRanges();
selection.addRange(range);
}
// Log selection changes to the console for debugging
document.addEventListener('selectionchange', (event) => {
const selection = window.getSelection();
console.log(selection.type + ': "' + selection.toString() + '"');
});
<p>Tap to select this paragraph.</p>
<p>Or this paragraph.</p>