Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  191] [ 7]  / answers: 1 / hits: 15748  / 13 Years ago, thu, november 3, 2011, 12:00:00

How to retrieve the position of selected text by calculating it's offset immediate after body tag?



For Example consider the following html,



<body> <div>hi</div> <div>dude!</div> </body>


on selecting from i (in hi) to du (in dude), I need to get 2 as start position & 4 as end position.



Note: Ignore the tag elements.



Javascript is preferable!


More From » jquery

 Answers
12

Here's some simple, naive code to do this that may well do the job for your use case. It does not take into account any text that may be made invisible (either by CSS or by being inside a or element, for example) and may have browser discrepancies (IE versus everything else) with line breaks, and takes no account of collapsed whitespace (such as 2 or more consecutive space characters collapsing to one visible space on the page). However, it does work for your example in all major browsers.



Live demo: http://jsfiddle.net/UuDpL/2/



Code:



function getSelectionCharOffsetsWithin(element) {
var start = 0, end = 0;
var sel, range, priorRange;
if (typeof window.getSelection != undefined) {
range = window.getSelection().getRangeAt(0);
priorRange = range.cloneRange();
priorRange.selectNodeContents(element);
priorRange.setEnd(range.startContainer, range.startOffset);
start = priorRange.toString().length;
end = start + range.toString().length;
} else if (typeof document.selection != undefined &&
(sel = document.selection).type != Control) {
range = sel.createRange();
priorRange = document.body.createTextRange();
priorRange.moveToElementText(element);
priorRange.setEndPoint(EndToStart, range);
start = priorRange.text.length;
end = start + range.text.length;
}
return {
start: start,
end: end
};
}

alert( getSelectionCharOffsetsWithin(document.body).start );

[#89320] Tuesday, November 1, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;