30 June 2011

Javascript and IE - Get the selection start and end

In Opera and other browsers it is fairly easy to get the start and end positions of the selection in a textarea. Exept, of course, in Internet Explorer, where you need these:

Get the start and end

function synGetCaret(editor) {
  if(document.selection){
    editor.focus();
    var range = document.selection.createRange();
    var range2 = range.duplicate();
    range2.moveToElementText(editor);
    range2.setEndPoint('EndToEnd', range);
    var selStart = range2.text.length - range.text.length;
    return new Array(selStart, selStart + range.text.length);
  }
}
The return value is an array with 0 = start and 1 = end.

Set the selection

As opposed to Opera and other browsers, IE also looses the selection in a textarea when that textarea looses the focus. Therefore you feed the array that was retrieved above in this function to restore the selection:

function synSetCaret(editor, selection) {
  if (document.selection) {
    if (selection[0] == NaN) selection[0] = 0;
    if (selection[1] == NaN) selection[1] = selection[0];
    if (editor.setSelectionRange) {
      editor.setSelectionRange(selection[0], selection[1]);
    }
    else if (editor.createTextRange) {
      var range = editor.createTextRange();
      range.collapse(true);
      range.moveEnd('character', selection[1]);
      range.moveStart('character', selection[0]);
      range.select();
    }
  }
}

No comments:

Post a Comment