Monday, 16 January 2023

Click to select all text in div not working on mobile

I want to select all text inside a div via a single click/tap. See example code (jsFiddle):

document.getElementById('target').addEventListener('click', function (event) {
  setTimeout(function() {
    window.getSelection().selectAllChildren(
            document.getElementById('target')
    )
  }, 100);
});
<div id="target">
  <span>click to select all </span>
  <span>text</span>
</div>

It works on desktop, but not properly on iOS using Safari (likely same problem on Android as well).

As you can see, I added a setTimeout() in an attempt to capture the mobile tap, but it only works after taping many times or focusing on the div via a long tap.

How can I make it select the full text with a single tap on iOS using pure JS?

Edit 1: Setting touchstart as event trigger might work, but avoiding it as it can be triggered by scrolling down the page and accidentally touching the element.

Edit 2: Making a bounty for a tested solution which works on iOS and mobile in general.



from Click to select all text in div not working on mobile

No comments:

Post a Comment