Cross Browser selectionStart/selectionEnd

Updated: 2005-10-23 01:00:16+0900 - [ HOME ]

Download

Usage

var selection = new Selection(document.getElementById("textAreaId"));
var s = selection.create();
alert("start:" + s.start + ", end:" + s.end);

Example

How to create selection from TextRange object.

  1. Create marker which is not included in the textarea contents.
    var marker = notIncludedRandomString(contents);
    
  2. Append marker before and after range.text.
    range.text = marker + range.text + marker;
    
  3. Get indexOf(marker).
    var selectionStart = contents.indexOf(marker);
    contents = contents.replace(marker, "");
    var selectionEnd = contents.indexOf(marker);
    
  4. Restore original contents (This is required because the last new lines is erased when the range.text is changed).
    textarea.value = originalContents;
    

Note


KOSEKI Kengo <kengo at tt.rim.or.jp>