Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML: Text in block-element; get exact position of click

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?

like image 388
Dennis Guse Avatar asked Mar 19 '23 13:03

Dennis Guse


1 Answers

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.

like image 90
Dennis Guse Avatar answered Apr 01 '23 22:04

Dennis Guse