javascriptselectiongetselection

Get start and end of a selection using javascript


i have an html string like this:

<div id="div">Hi how are<span>you?</span> Fine</div>

The text will appear "Hi how are you? Fine".

I would like to select a part of the string using mouse and get the beginning and the end of the selection looking from the full text string.

For example, if i select "you", i would like to obtain start=11 and end=14;

if i select "are you?", i would like to obtain start=7 and end=15.

I wrote this to obtain the selection:

function getSel() {
            console.log(navigator.appCodeName);
            if (window.getSelection) {
                return window.getSelection();
            } else if (document.getSelection) {
                return document.getSelection();
            } else if (document.selection) {
                return document.selection.createRange().text;
            }
        }

And this code to obtain start and end, but it doesn't work:

$("#div").on('mouseup', function(e){
            var text=getSel();
            if(text.anchorNode === text.focusNode){
                var n = {  
                    node: text.anchorNode.parentNode.id,
                    start: text.anchorOffset,
                    end: text.focusOffset
                }
                //selection from right to left
                if(n.start>=n.end) {  
                    var tmp;
                    tmp=n.start;
                    n.start=n.end;
                    n.end=tmp;
                }
            }
            else    console.log("error in selection");          
});

Solution

  • Your selector is wrong. $('#div') actually selects for any elements that have id='div'.

    I have made an example of how it's done. If I am not mistaken of what you're trying to achieve.

    function getSelectionText() {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return text;
    }
    
    $(function(){
      $("#div").on('mouseup', function(e){
        var thisText = $(this).text();
        var selectedText = getSelectionText();
        var start = thisText.indexOf(selectedText);
        var end = start + selectedText.length;
        if (start >= 0 && end >= 0){
            console.log("start: " + start);
            console.log("end: " + end);
        }
      });
    });
    

    Fiddle