I was looking for a javascript to get in a div the start position, length and the div id of a selection on a webpage. I found that topic which answered almost all my needs (Determine the position index of a character within an HTML element when clicked).
It basically is everything I want, except I have spans in my divs, and when selecting text inside or after a span, the anchorOffset relates to the last span in the div.
I thought of working this out by :
1) getting the parentNode.innerHTML and deleting the spans opening and closing tags from it
2) Finding the selection.anchorNode content position inside 1) with substring ()
3) Adding 2) + AnchorOffset
Although, this leaves me with 2 problems: - In 2), in the case I click inside a span, it might contain text that repeats itself inside the div, in which case, is there a way to make sure I am getting the position of the right one?
Also, is there any other way you would advise to do it differently?
Thanks in advance for the help!
javascript code:
$('div, span').click( function () {
var infos = getSelectionPosition();
});
function getSelectionPosition () {
var selection, div_content, selection_start, selection_length, div_id;
console.clear();
selection = window.getSelection();
div_id = selection.focusNode.parentNode.id;
console.log("div_id is "+div_id);
div_content = selection.focusNode.parentNode.innerHTML;
div_content = div_content.replace("</span>","");
div_content = div_content.replace(/<span class="source-in-text" id="s[0-9]*" style="">/,"");
selection_start = div_content.search(selection.toString());
console.log(selection_start);
selection_length = selection.toString().length;
console.log("selection_length is "+selection_length);
return [div_id, selection_start, selection_length];
}
<div id="p2">Duis tincidunt risus eget metus semper porttitor. Etiam sapien erat, interdum eget tortor in, fermentum facilisis leo. <span class="source-in-text" id="s1">Curabitur pulvinar </span> orci leo, non laoreet eros rhoncus vel. Vestibulum in nibh viverra, tristique dolor sed, consectetur nisl. Phasellus non sem ac enim ultricies lacinia mattis at nulla. Sed id vehicula orci. Nullam non nisi vitae lectus ultrices sodales.</div>