Skip to content Skip to sidebar Skip to footer

Calculating Start And End Selection Indices In HTML Through Javascript

How can I get the start and end selection indices in browsers other than IE in contentEditable 'div'. For Ex., IE has the following method. var oSelection; var oTxtRange; var units

Solution 1:

You can do something like the following in non-IE browsers. It returns offsets of the selection boundaries within the visible body text of the page like the IE version does, but I'm not sure what use these numbers will be.

function getBodyTextOffset(node, offset) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(document.body);
    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
    };
}

Post a Comment for "Calculating Start And End Selection Indices In HTML Through Javascript"