Contenteditable Div - Cursor position in terms of innerHTML position
Asked Answered
B

1

6

I've done my research and come across these questions on StackOverflow where people asked this same question but the thing is that they wanted to get the position either in terms of x and y coordinates or column from the left. I want to know what the position of the cursor is with respect to the div's innerHTML.

For example:

innerHTML = "This is the innerHTML of the <b>div</b> and bla bla bla..."
                                                        ^
                                                  Cursor is here

So the result I want for this case is 44. How to do it ?

Bombshell answered 25/3, 2015 at 13:43 Comment(4)
can you define " want to know what the position of the cursor is in terms of the position of the cursor with respect to the div's innerHTML"? why it should be 44?Gastrotrich
sorry! brain malfunction. I edited the post. @FrancescoE.Bombshell
I see you accepted an answer, so it is resolved, isn't it?Gastrotrich
Why do you want this? It's essentially meaningless: there isn't a single HTML representation of element's content.Toe
R
7
var target = document.createTextNode("\u0001");
document.getSelection().getRangeAt(0).insertNode(target);
var position = contentEditableDiv.innerHTML.indexOf("\u0001");
target.parentNode.removeChild(target);

This temporarily inserts a dummy text node containing a non-printable character (\u0001), and then finds the index of that character within the div's innerHTML.

For the most part this leaves the DOM and the current selection unchanged, with one minor possible side effect: if the cursor is in the middle of text from a single text node, that node will be broken up into two consecutive text nodes. Usually that should be harmless, but keep it in mind in the context of your specific application.

UPDATE: Turns out you can merge the consecutive text nodes using Node.normalize().

Rolle answered 25/3, 2015 at 14:35 Comment(2)
This is having some undesired side effects when I hit the delete button. Seems like I'm not deleting the character I want to when I use this.Germano
why is it "\u0001"? Why do you not use "\u0000" to make it simple? Is there something special about "\u0001"?Hydrate

© 2022 - 2024 — McMap. All rights reserved.