views:

178

answers:

2

I've searched for days but couldn't find one solid solution to get the selection start / end in Internet explorer, I've tried this and this solution.

Both of them involve using document.selection.createRange(), the below code will work quite good but if you go to a new line (press enter one or more time) and then try to get the selection start/end you will end up before you pressed enter. From what I see createRange() won't select the latest empty line breaks, I don't want the code to get too messy so is there a different solution for this?

function selecetion_range()
{
 var range = document.selection.createRange();
    var stored_range = range.duplicate();
    stored_range.moveToElementText(textarea[0]);
    stored_range.setEndPoint('EndToEnd', range );

    return {
       start: stored_range.text.replace(/\r/g,'').length - range.text.replace(/\r/g,'').length,
       end: stored_range.text.replace(/\r/g,'').length
 }
}

edit:

To clarify the problem, lets say my cursor is at the end of this quote:

"some random text

<here>"

once I use the above code the selection start would be:

"some random text<here>"

A: 

You might find useful http://code.google.com/p/ierange/ project. Some details are available also from http://ajaxian.com/archives/ierange-implementing-w3c-dom-ranges-for-ie

Sergey Ilinsky
Nice. However, that project suffers from the same problem outlined by the asker with respect to newlines in the selected text: http://code.google.com/p/ierange/issues/detail?id=4
Crescent Fresh
A: 

Found the solution here, its a huge code block so I don't want to post the answer here.

Dennis