Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

How can I get the start and end selection indices in browsers other than IE in contentEditable 'div'. For Ex., IE has the following method.

C#
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 above method is not a W3C standard. I have gone through W3C documentation for Selection and Range object, but still couldn't help finding solution for Chrome and FireFox.

Thanks in Advance :-)
Posted

1 solution

Hi All,

Finally I found the following solution for Non-IE browsers.

C#
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
    };
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900