Computing the start and end indices of a selection in HTML via Javascript

How can I get the start and end indices of a selection in non-IE browsers in a contentEditable 'div'. For example, IE has the following method.

var oSelection;
var oTxtRange;
var units = -100000;
var iStartIndex = -1, iEndIndex = -1;

if(document.selection)      // IE..
{
  oSelection = document.selection;
  oTxtRange = oSelection.createRange();

  if(oTxtRange)
  {
    iStartIndex = oTxtRange.moveStart('character',units);
    iEndIndex = oTxtRange.moveEnd('character',units);
    iStartIndex *= -1;
    iEndIndex *= -1;
  }
}

I understand that the above method is not a W3C standard. I looked at the W3C documentation for the Selection and Range object, but still couldn't find a solution for Chrome and FireFox. A solution in jQuery is also welcome.

Thanks in advance: -)

0
source share
1 answer

In browsers other than IE, you can do something like the following. It returns the selection border offsets within the visible body of the page, like the IE version, but I'm not sure what numbers to use.

function getBodyTextOffset(node, offset) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(document.body);
    range.setEnd(node, offset);
    sel.removeAllRanges();
    sel.addRange(range);
    return sel.toString().length;
}

function getSelectionOffsets() {
    var sel, range;
    var start = 0, end = 0;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(sel.rangeCount - 1);
            start = getBodyTextOffset(range.startContainer, range.startOffset);
            end = getBodyTextOffset(range.endContainer, range.endOffset);
            sel.removeAllRanges();
            sel.addRange(range);
            alert(start + ", " + end);
        }
    } else if (document.selection) {
        // IE stuff here
    }
    return {
        start: start,
        end: end
    };
}
0
source

All Articles