493: Undecipherable

-Blog-

-Projects-

-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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 wanted 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.

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.