1

I am trying to get the starting and ending points of user selection. This is the content of a DIV that I have

abc def ghi jkl mno pqr stuv wxyz

When I select pqr The starting point becomes 1 and the ending point becomes 4 which is wrong

When I select the whole thing, the starting point becomes 0 and the ending point becomes 33 which is right

I have the following code:

    sel = window.getSelection();
    le = sel.toString().length;

    if (sel.getRangeAt && sel.rangeCount)
    {
        range = window.getSelection().getRangeAt(0);
        sp = range.startOffset;
        ep = sp + le;               
    }
Eyad Fallatah
  • 1,859
  • 4
  • 22
  • 34

1 Answers1

3

Rangy to the rescue! Use this api to get everything about user selection.
It supports browser:

  1. Internet Explorer 6 and later (:D)
  2. Firefox 2.0 and later
  3. Google Chrome 5.0 and later
  4. Safari 3.2 and later
  5. Opera 9.6 and later

Using it

Read the documentation yourself, or just use the below.
Very simple (in your case),

var selection = rangy.getSelection(),  //Whole lot of information, supports
                                       //multi-selections
    start=selection.anchorOffset,      //Start position
    end=selection.focusOffset;         //End position

Hope it helps you out.

Demos

You can find demos on its home page.
Here are some that might help you out and might find interesting:

  • Demo 1 - Core, the main thing
  • Demo 4 - Change the CSS of the selected range
  • Demo 3 - Serializing selection(s)
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247