I am trying to include functionality that will enable a user to highlight text and have that text returned. I would also like to return the location of that text within #textcontainer div.
My issue: if the user highlights the second 'and' in the text below, position will equal the indexOf the first 'and' in the div instead of the second. How do I change this to have position return the position of the second 'and' (the one that is highlighted)?
<div id = 'textcontainer'>
and second third and
</div>
// beginning of highlight js
$('#highlight').click(function (e) {
e.preventDefault();
// get highlighted text
var selection = window.getSelection();
var txt = selection.toString();
console.log(txt);
fulltext = $("#textcontainer").text();
console.log(fulltext);
position = fulltext.indexOf(txt);
console.log(position);
})
// end of highlight js