views:

55

answers:

2

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.

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. Solution in JQuery is also welcome.

Thanks in Advance :-)

A: 
  var textarea = document.getElementById("oSelection");

  var len = textarea.value.length;
   var start = textarea.selectionStart;
   var end = textarea.selectionEnd;
   var sel = textarea.value.substring(start, end);

   // This is the selected text and alert it
   alert(sel);

  var replace = '<b>' + sel + '<b>';

  // Here we are replacing the selected text with this one
 textarea.value =  textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);
PRS
That only applies to text inputs and textareas.
Tim Down
A: 

You can do something like the following in non-IE browsers. It returns offsets of the selection boundaries within the visible body text of the page like the IE version does, but I'm not sure what use these numbers will be.

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
    };
}
Tim Down
Hi Tim, your solution works. Great. And about the scenario where I am using it is like this. Suppose, you make <body> as contentEditable, and you want to allow user to typing at particular position say in-between <span id='allowTyping'>Hello</span> element. At that time, to make sure that selection is within that element while typing. Thank you very much. :-)
Ammar Bharmal