I need to now where in a html block-element that contains only text a click happened:
<div>This is some awesome text</div>
I would like to get the position of the letter that was clicked. Limitation: it is not possible to add additional childs to the div.
Any options?
Solution I adopted thanks to @TimDown is taken from Mozilla.
function insertBreakAtPoint(e) {
var range;
var textNode;
var offset;
if (document.caretPositionFromPoint) { // standard
range = document.caretPositionFromPoint(e.pageX, e.pageY);
textNode = range.offsetNode;
offset = range.offset;
} else if (document.caretRangeFromPoint) { // WebKit
range = document.caretRangeFromPoint(e.pageX, e.pageY);
textNode = range.startContainer;
offset = range.startOffset;
}
// do whatever you want here!
}
There is one limitation (at least I have a small problem in Chromium) that the range.textNode must not necessarily identical to the one that was clicked. The contained text might be shorter than expected. Reason for that remained unknown. I just did the access via range.textNode.parentElement.firstChild as in my case the div only has one child.
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