1

I am still working on a little Code Editor project, and I already succeded doing some syntax highlight features. But when I tried it, I faced a little problem :

After doing all the changes (changing tags colors by adding special span arround those), the user cursor is going right at the beginning of the contenteditable body. This is kind of annoying for the user, if each time he add a new tag he must click again in the right place to continue typing is code.

The problem is bigger since the function which check the latest changes in the syntax is called every time the user is typing. So for example, if he typed a <a href="http://www.google.com"> tag, the cursor will go back at the beginning, but even if he click again after the last >, the function will be called as soon as he type another key and the cursor will go back at the beginning, which means that he can't write after the link...

I already searched a lot and found various articles and topics with the same question, but none of them worked :

  • I was using the getCharacterOffsetWithin function, but since it works only with a single line I can't use thise one.
  • The answer proposed by @TimDown doesn't work in my case, because I may have multiple tags inside each others.
  • And the function provided by @Sorunome doesn't work neither, even if it doesn't raise any error, but the cursor is still going at the beginning.

I am kind of lost with this, because I was supposing that getting and setting a cursor position was something pretty easy, but it seems that there is no simple answer to this problem.

My question is: should I create my own GetCursorPosition() and SetCursorPosition(), considering my special case, or is there any way with Javascript or jQuery to get and set a cursor position inside an entire contenteditable body that I could have missed ?

Louis 'LYRO' Dupont
  • 1,052
  • 4
  • 15
  • 35
  • As far as I know there is no other way than using selection and range APIs. You should set a range after the node you've created (range.setStartAfter) and add that range to selection so your cursor can move to the end of the span. We can work on it if you can share some code maybe. – cdagli Aug 07 '17 at 18:08

0 Answers0