views:

1097

answers:

3

I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows:

var delselection = window.getSelection();

var startOffset = delselection.anchorOffset;

var endOffset = delselection.focusOffset;

var startNode = delselection.anchorNode.parentNode;

var endNode = delselection.focusNode.parentNode;

However i have no idea how to do this in IE6, anyone able to point me in the right direction?

+1  A: 

You should look at the ControlRange and TextRange objects of the IE BOM.

AnchorOffset,focusOffset and window.getSelection() are not supported by IE6/7 I believe.

Ash
anchorOffset etc are firefox methods for dealing with selection just put them there to give an idea what i was attempting. The textRange object just gives an offset in relation to the edge of the document so i assume its in pixles, and i don't think you can use the controlRange object with selection
+2  A: 

document.selection.

However the TextRange object returned by IE does not match Firefox/WebKit/W3's, and determining the exact positions of the start and end points is very frustrating. Depending on what exactly you are doing with the range you may be able to get somewhere with range.parentElement(), range.inRange() or range.compareEndPoints(). For rich text editors you will usually end up using the staggeringly ugly range.execCommand() interface.

The IE Range implementation is so odd and different to the Mozilla/Webkit/W3 model that you typically end up with completely different code paths for everything to do with selections between the two.

bobince
Working with selection and range across all browsers is excruciating, and not for the faint of heart. These are good tips, thanks bobince!
Jason
A: 

If you know the object the selection is in (e.g., it's an input field the user is typing in that you want to change while they're typing), this code does the trick:

var selObj = null;
var selSave = null;
var selSaveEnd = null;

function SaveSelection(obj) {
    if (obj.selectionStart) {
     selObj = obj;
     selSave = obj.selectionStart;
     selSaveEnd = obj.selectionEnd;
    }
    else {
     // Internet Explorer case
     selSave = document.selection.createRange();
    }
}

function RestoreSelection() {
    if (selObj) {
     selObj.focus();
     selObj.selectionStart = selSave;
     selObj.selectionEnd = selSaveEnd;
    }
    else {
     // Internet Explorer case
     selSave.select();
    }
}
Roy Leban