3

I'm having trouble selecting text on my site. I have a div block and want all the text inside to be selected when the div block is touched on iPhone/Android. So far I've tried the method at: Selecting text in mobile Safari on iPhone

Like so:

<div ontouchstart="this.selectionStart=0; this.selectionEnd=this.value.length;">

I also tried creating a function in my JS file to do this based on recommendations from different sources:

HTML

<div ontouchstart="touchStart(event, this);>

JS

function touchStart(event, obj) {
  var range = window.getSelection();
  var sel = window.getSelection()

  range.setStart(obj, 0);
  range.setEnd(obj, obj.innerHTML.length);
  sel.removeAllRanges();
  sel.addRange(range);
  //range.execCommand("BackColor", false, colour);
}

So far neither method seems to work. One error I seem to get using the second method while testing on Safari on iPhone is:

JavaScript: Error undefined TypeError: 'undefined' is not an object
Community
  • 1
  • 1
Zaheer
  • 2,794
  • 5
  • 28
  • 33

1 Answers1

0

selectionStart and selectionEnd are properties of textareas and text inputs only, so they're out. Mobile Safari has the same selection API as all other major browsers but you can only affect the visible selection if it's already displayed.

HTML:

<div ontouchstart="selectElementContents(this);">

JS:

function selectElementContents(el) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(el);
    sel.removeAllRanges();
    sel.addRange(range);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 2
    I'm not sure I follow the last point, "you can only affect the visible selection if it's already displayed". I tried this out on my site on iPhone 4s and it did not work. Sort of goes into a weird state where the text inside div is not selectable. Also tried it on JSFiddle: http://jsfiddle.net/tJa5g/ – Zaheer Sep 11 '12 at 01:24