We can use the document.getSelector
to get the selection.
And then we can use that to get the length of the selection to get the cursor position.
For instance, we can write the following HTML:
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
Then we can write the following JavaScript code to get the location of the cursor by writing:
const cursorPosition = () => {
const sel = document.getSelection();
sel.modify("extend", "backward", "paragraphboundary");
const pos = sel.toString().length;
if (sel.anchorNode != undefined) sel.collapseToEnd();
return pos;
}
const elm = document.querySelector('[contenteditable]');
const printCaretPosition = () => {
console.log(cursorPosition(), 'length:', elm.textContent.trim().length)
}
elm.addEventListener('click', printCaretPosition)
elm.addEventListener('keydown', printCaretPosition)
We have the cursorPosition
function that calls the documebnt.getSelection
method to get the text inside the div.
Then we call modify
to adjust the current selection.
We move 'backward'
by 'paragraphboundary'
.
Then we get the length of the selection after converting it to a string.
And then we collapse the selection and return pos
to return the position of the cursor.
Next, we get the div with querySelector
.
And then we create the printCaretPosition
to print the cursor position.
Finally, we call addEventListener
so that we call printCaretPosition
when we click or type on the div.