0

I don't feel very conformtable with JS so I need your help to get a solution.

I have to catch logs from users about their text selection and copy in html pages. Then I need to get an unique position for each selection (because 2 selections can contain the same text and be at different positions).

In my JS script, I have a function that returns me an object "range". I can use the "startOffset" and "endOffset" of the range to get the position of the first and the last element of the selection, but these offsets are only determined from the start of the node (ex. p or h1).

So my question is : is there a way to get the offsets from the start of the whole html page ?

Here is my code :

function getSelectionRange() {
    var range;
    if (window.getSelection) {
        range = window.getSelection().getRangeAt(0);
    } else if (document.selection && document.selection.type != "Control") {
        range = document.selection.getRangeAt(0);
    }
    return range;
}


$(document).bind('copy', function() {         // detects the copy
    var range = getSelectionRange();
    alert(range.startOffset+" "+range.endOffset);
    // then save in logs
}); 

Thanks in advance

TheDahaka
  • 33
  • 6
  • I think you should think of a hack because this function only get you the offset for the inner element the text is incorporated (see this [**JSFiddle**](https://jsfiddle.net/3Lgmvzqn/) for a demo. – Anwar Dec 22 '15 at 08:35
  • Yes I know it's precisely my problem. I need the offset for the start of the document and not for the inner element. But I don't know how :( – TheDahaka Dec 22 '15 at 08:38
  • That's ok I found my answer there : http://stackoverflow.com/questions/7991474/calculate-position-of-selected-text-javascript-jquery?rq=1 – TheDahaka Dec 22 '15 at 09:18

0 Answers0