Set selection range in javascript IE8
Asked Answered
P

2

6

I'm working on a wysiwyg editor using div[contenteditable=true] and I want to set a selection range from offset X of Node A to offset Y of Node B. I did it well on Firefox and IE9, the code is :

var range = document.createRange();
range.setStart(selectNode, 0);
range.setEnd(selectNode, selectNode.textContent.length);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

But on IE8, the range object is totally different, it has no setStart/setEnd, and the selection object has no remove/addRange stuffs. Please help,

Perforce answered 16/12, 2011 at 4:20 Comment(0)
H
4

Take a look at rangy. Its a cross browser range/selection API. That's probably what you need.

http://code.google.com/p/rangy/

Hackney answered 16/12, 2011 at 4:41 Comment(1)
Rangely-core.js is 42kb compressed which might be a design consideration.Oceangoing
K
3

I had a similar problem found this polyfill which was quite useful to me, as I could not use rangy in my situation: http://bl.ocks.org/visnup/3456262

Edit: original link has indeed gone dead. Looking back over my old code it looks like the polyfill never made it into the release code, we simply went with feature detection as follows:

if(window.getSelection || document.selection){

then on mouseup:

var range;
if(window.getSelection){
    var selection = window.getSelection();
    range = selection.getRangeAt(0);
} else if(document.selection){
    range = document.selection.createRange();
    if(!range.surroundContents){
        // then give up, feature not fully implemented
    }
}
// now do stuff with range (i.e. the selection)

...and the IE8 users are therefore not supported for that feature.

However all is not lost: there's a newer (than my original answer) polyfill on Github which might work if you have to support IE8. It looks both pretty lean and comprehensive.

Kicker answered 20/4, 2014 at 16:33 Comment(4)
This solution is only 800 bytes compressed and targets IE8 per requirement. This might be a better solution in contrast to Rangely.js which is much heavier.Oceangoing
This works like a charm for me too and I think it's the best way to do it.Spool
Link is dead. Could someone provide a new link?Kyanize
I've added to my original answer as the link is indeed dead.Kicker

© 2022 - 2024 — McMap. All rights reserved.