Reputation: 5264
I am trying to get the caret position for some text inside an iframe in design mode, in IE8. The code I have works, but for long texts it performs badly and ugly, because it selects all the text and then starts moving the end of the range one character at a time.
I wonder if there is a faster and more elegant way to get the current caret position in IE? here is my current code:
var r = doc.selection.createRange();
r.collapse(false);
doc.execCommand("SelectAll") //this is ugly..
var r2 = doc.selection.createRange();
r2.select();
//..and this is slow
while (r.compareEndPoints("EndToEnd", r2) < 0) {
r2.moveEnd("character", -1)
r2.select();
}
pos = r2.text.length;
Upvotes: 0
Views: 597
Reputation: 324627
Yes, you can use my Rangy library, which gives you a single way of doing this in all browsers using the DOM Level 2 Range interface. The following assumes you have the iframe's window
object stored in a variable called iframeWin
:
var sel = rangy.getSelection(iframeWin);
if (sel.rangeCount > 0) {
var selectedRange = sel.getRangeAt(0);
alert(selectedRange.toString());
}
The process used to convert IE's TextRange
objects into DOM Range objects in Rangy is more sophisticated and much faster (for long documents, at least) than what you already have. If you're interested, the relevant code is near the top of this file: http://code.google.com/p/rangy/source/browse/trunk/src/js/core/wrappedrange.js
Upvotes: 3