Selecting text in mobile Safari on iPhone

21,186

Solution 1

instead of this.select(); I used the following and it worked!

this.selectionStart=0;
this.selectionEnd=this.value.length;

Solution 2

The magic sauce for me was the combination of these three:

onFocus="this.selectionStart=0; this.selectionEnd=this.value.length;" <!-- for big screens -->

onTouchEnd="this.selectionStart=0; this.selectionEnd=this.value.length;" <!-- for small screens -->

onMouseUp="return false" <!-- to stop the jitters -->

Solution 3

Try ontouchstart instead of onfocus. Onfocus fires approx. 500ms after ontouchend, same as onclick, onmousedown, and onmouseup. See https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW7 for more details on mouse events.

Solution 4

I have run into the same problem. The onfocus event is the right one to trap (ontouchstart isn't triggered if you use the iphone keyboard [next]/[prev] buttons.) If you put an alert(); in your onfocus="" handler, you'll see the alert box pop up. The problem is this.select(); I still haven't found an answer to this, but when/if I do, I'll post it here.

Share:
21,186
Volodymyr Belozorov
Author by

Volodymyr Belozorov

Updated on July 09, 2022

Comments

  • Volodymyr Belozorov
    Volodymyr Belozorov almost 2 years

    I'm trying to make it easy for an iphone user to copy some text to the clipboard in mobile safari. As in the usual "touch-hold-copy". There is a specific bit of text I want to a user to copy. I have full choice of the html markup in which to wrap the text. How can I make it easy, rather than abitrary? For instance:

    • Is there a way to "select all" the text upon touch-down using javascript? Then a user could just continue to touch-hold and then choose copy?

    • Is there a way to bring up the "select all" option? Like you can when typing in a text box? After which they can choose copy?

    • If there's no javascript solution, how can I arrange the html to help Safari select the right bit of text easily? As opposed to just a word, or a wrapping div?

    I've tried onFocus="this.select()" for various elements, none seem to work. Also tried onClick.

    Those who have tried to port a site that uses ZeroClipboard to the iPhone might have some ideas.

    Cheers