Question

In the following code:

var s=window.getSelection();
var sr=s.getRangeAt(0);

console.log(s.anchorOffset+" "+s.focusOffset);

s.removeAllRanges();
s.addRange(sr);

console.log(s.anchorOffset+" "+s.focusOffset);

The anchorOffset and focusOffset are swapped when replacing a range. i.e. The anchor resets to the leftmost end of the selection and the focus to the rightmost, regardless of from which end the selection actually started and ended. It seems the anchor and focus are ignored when adding a range (or at least not stored), and it defaults and assumes left anchor and right focus.

This is a damn nuisance!

I don't hold out much hope, but is there any way I'm missing that I can work around this behavior. I would really love to be able to restore the original anchor and focus positions.

Works same in chrome and firefox.

EDIT

Ok have worked out a partial answer:

var s=window.getSelection();
var sr=s.getRangeAt(0);

console.log(s.anchorOffset+" "+s.focusOffset);

var aN=s.anchorNode,aO=s.anchorOffset,fN=s.focusNode,fO=s.focusOffset;

s.removeAllRanges();
s.addRange(sr);

s.collapse(aN,aO);
s.extend(fN,fO);

console.log(s.anchorOffset+" "+s.focusOffset);

HOWEVER, this won't work in IE9+ as IE doesn't implement the extend method. So now the question becomes, how to make IE play nice in this regard?

Was it helpful?

Solution

No. It's just impossible in IE. I raised a bug in the IE bug tracker a year ago suggesting they implement extend() but it hasn't happened and now they've closed the bug it seems unlikely to happen any time soon.

UPDATE: The IE bug has been reopened so there is hope.

Here are my answers to two similar questions:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top