I have this function to get position of the cursor when you click on the text, it only works for monospace characters which is fine, but it obviously don\'t work with charac
window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.charPosition').forEach(el => {
let characters = el['innerText'].split('');
el.innerHTML = '';
characters.forEach(char => {
let span = document.createElement('span');
span.innerText = char;
span.addEventListener('click', function () {
let position = 0;
let el = this;
while (el.previousSibling !== null) {
position++;
el = el.previousSibling;
}
console.log(this.innerHTML + ':' + position);
});
el.appendChild(span);
});
});
});
<div class="charPosition">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
Third attempt. Stuff a pipe character in there to pretend to be a cursor.
https://developer.mozilla.org/en-US/docs/Web/API/Selection
window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.charPosition').forEach(el => {
let clean, cursor;
el.addEventListener('click', e => {
let position = window.getSelection().focusOffset;
if (cursor && position > cursor)
position--;
if (clean)
el['innerText'] = clean;
let textnode = el.firstChild['splitText'](position);
clean = textnode.wholeText;
cursor = position;
el.insertBefore(document.createTextNode('|'), textnode);
el['innerText'] = textnode.wholeText;
});
});
});
<div class="charPosition">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>