I am looking for a way to calculate the start and end position of a user selection from a known parent. I came across this with some small changes that I managed to get in FF, but I'm not sure how to do this in IE, and I would love to have some thoughts if my modification is suitable. Many thanks to Tim Down for the original answer.
function getBodyTextOffset(node, offset) {
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(document.getElementById('test'));
range.setEnd(node, offset);
sel.removeAllRanges();
sel.addRange(range);
return sel.toString().length;
}
function getSelectionOffsets() {
var sel, range;
var start = 0, end = 0;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(sel.rangeCount - 1);
start = getBodyTextOffset(range.startContainer, range.startOffset);
end = getBodyTextOffset(range.endContainer, range.endOffset);
sel.removeAllRanges();
sel.addRange(range);
alert(start + ", " + end);
}
} else if (document.selection) {
}
return {
start: start,
end: end
};
}
I know it has been a while, but here is a JSFiddle demonstrating this idea. Again, it works in FF and Chrome, but not in IE9. Ideally, I would like to get the offset from the start of the element test.
source
share