Calculate start and end position of user selection using javascript from parent element

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) {
        // IE stuff here
    }
    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.

+5
source share
1

JavaScript - , ...

, ...

http://dylanschiemann.com/articles/dom2Range/dom2RangeExamples.html

, , ... http://help.dottoro.com/ljxsqnoi.php

, , JavaScript...

for (i in window.getSelection()) {alert('i = '+i);}

, , , , , , ...

for (i in window.getSelection().getRangeAt(0)) {alert('i = '+i);}

, Gecko (, Firefox), , , 50% /, Gecko . , , , Mozilla ( , ), , ...

https://bugzilla.mozilla.org/show_bug.cgi?id=696571

, .

+1

All Articles