views:

317

answers:

3

Hi guys

is there a way to get the highlighted selectionstart and selectedlenght on a span ?

Thanks

A: 

You might find some answers in this quirksmode post:

klaaspieter
Hi, Thank you for your quick response. Problem here is that when a user select a text fragment on a particular span (asp.net label), i need to get the selected start and end? is there anyway that i could do this ?
kakopappa
A: 

Have a try on this:

  var span = document.getElementById('span1');
  if (document.selection) { //IE
      var bm = document.selection.createRange().getBookmark();
      var sel = span.createTextRange();
      sel.moveToBookmark(bm);

      var sleft = span.createTextRange();
      sleft.collapse(true);
      sleft.setEndPoint("EndToStart", sel);
      span.selectionStart = sleft.text.length
      span.selectionEnd = sleft.text.length + sel.text.length;
      span.selectedText = sel.text;
  }
  else if (span.selectionStart){ //FF
     span.selectedText = span.substring(span.selectionStart,span.selectionEnd);
  }

  alert("Selection Start==> " + span.selectionStart + "\n" +
     "Selection End  ==> " + span.selectionEnd + "\n" +
     "Selected Text  ==> " + span.selectedText + "\n" +
     "TextArea Value ==> " + span.value);
jerjer
Thanks, but span.createTextRange(); gives an error. it only supports for textarea
kakopappa
use createRange() instead.
jerjer
A: 

I use my own optimization of the algorithms in IERange, which provides a wrapper around IE's TextRange (which is what you get from the selection in IE) to give them the same interface as DOM Ranges.

To get the selection in the document, use something like the following:

var sel = window.getSelection(); // Provided by IERange in IE, built-in in other browsers
var range = sel.getRangeAt(0); // Note this doesn't work in Safari 2

range now has properties startContainer and startOffset, which are respectively a reference to a node and an offset within that node that represent the start of the selection, and corresponding properties endContainer and endOffset that represent the end of the selection.

Tim Down
it worked .. thanks a lot .
kakopappa