Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selection range in javascript IE8

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,

like image 471
camapcon Avatar asked Dec 16 '11 04:12

camapcon


2 Answers

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

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

like image 100
techfoobar Avatar answered Oct 01 '22 15:10

techfoobar


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.

like image 25
Coder Avatar answered Oct 01 '22 15:10

Coder