I am trying to find the position of the selected text in a div. I prompt the user to select a substring of the text in a div and then submit it. I need the index of the start point and end point and have not been successful using the strategy below. Any help would be much appreciated.
This is the function I have and it is not working:
if (typeof window.getSelection != 'undefined') {
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var preCaretRange = range.cloneRange();
startOffset = preCaretRange.toString().length;
endOffset = startOffset + range.toString().length;
}
The div is called "myarea". Thanks
You almost got it right!
Its the startOffset which is causing it not to work.
Currently it is:
var startOffset = preCaretRange.toString().length;
The value on the RHS which is preCaretRange.toString().length is going to return you the total length of the string which has been selected, and not the start position. To get the start position you would use the startOffset property stored by the range. Therefore:
var startOffset = preCaretRange.startOffset;
A note on optimization: you do not need to clone range into preCaretRange..
document.body.addEventListener('mouseup', function () {
if (typeof window.getSelection != 'undefined') {
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var startOffset = range.startOffset;
var endOffset = startOffset + range.toString().length - 1;
console.log("Selection starts at: " + startOffset);
console.log("Selection ends at: " + endOffset);
}
}, false);
Here is a fiddle which demonstrates it working with an actual text selection: http://jsfiddle.net/Dp3qp/3/
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