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,
Take a look at rangy. Its a cross browser range/selection API. That's probably what you need.
http://code.google.com/p/rangy/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With