493: Undecipherable

-Blog-

-Projects-

-Urlaub-

-About me-

-RSS-

HTML: which letter was clicked in text?

Dennis Guse

For my spare-time project TheSchreibmaschine I need to get the position of the letter in a div that was clicked.

Limitation: it is not possible to add additional childs to the div.

1 <div>This is some awesome text</div>

The solution is actually quite straight forward: just capture the mouse event and ask the document to calculate the caret-position using the mouse coordinates.

Here is the solution I adopted:

 1 function insertBreakAtPoint(e) {
 2 
 3     var range;
 4     var textNode;
 5     var offset;
 6 
 7     if (document.caretPositionFromPoint) {    // standard
 8  range = document.caretPositionFromPoint(e.pageX, e.pageY);
 9  textNode = range.offsetNode;
10  offset = range.offset;
11     } else if (document.caretRangeFromPoint) {    // WebKit
12  range = document.caretRangeFromPoint(e.pageX, e.pageY);
13  textNode = range.startContainer;
14  offset = range.startOffset;
15     }
16     // do whatever you wanted here!
17 }

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.

The 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, which is the text.

For further reference the stackoverflow. Thanks to @TimDown.