I am trying to apply style to the text selected by the user(mouse drag) for which I need to get the start and end index of the selected text.
I have tried using "indexOf(...)" method. but it returns the first occurrence of the selected substring. I want the actual position of the substring with respect to the original string. For example.., if I select the letter 'O' at position 3 [YOLO Cobe], I expect the index as 3 but the indexOf() method returns 1 which is the first occurrence of 'O' in [YOLO Cobe].
Is there any other method of getting the actual start and end index of selected text and not the first occurrence ?
function getSelectionText()
{
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
document.getElementById('ip').addEventListener('mouseup',function(e)
{
var txt=this.innerText;
console.log(txt);
var selectedText = getSelectionText();
console.log(selectedText);
var start = txt.indexOf(selectedText);
var end = start + selectedText.length;
if (start >= 0 && end >= 0){
console.log("start: " + start);
console.log("end: " + end);
}
});
<div id="ip">YOLO Cobe</div>
getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.
<input type="button" onmousedown="alert(isTextSelected(document. getElementById('test')));" value="Selected?">
What you are looking for is available inside object returned by window.getSelection()
document.getElementById('ip').addEventListener('mouseup',function(e)
{
var txt = this.innerText;
var selection = window.getSelection();
var start = selection.anchorOffset;
var end = selection.focusOffset;
if (start >= 0 && end >= 0){
console.log("start: " + start);
console.log("end: " + end);
}
});
<div id="ip">YOLO Cobe</div>
And here is example for more complex selections on page based on @Kaiido comment:
document.addEventListener('mouseup',function(e)
{
var txt = this.innerText;
var selection = window.getSelection();
var start = selection.anchorOffset;
var end = selection.focusOffset;
console.log('start at postion', start, 'in node', selection.anchorNode.wholeText)
console.log('stop at position', end, 'in node', selection.focusNode.wholeText)
});
<div><span>Fragment1</span> fragment2 <span>fragment3</span></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With