0

I m trying to reformat some text inside an HTML code tag, via onkeypress event. But after text changing, the cursor goes the start position. I must keep the current position of the cursor.

To prevent this problem I found this;

this.selectionStart = this.selectionEnd = this.value.length;

from: Use JavaScript to place cursor at end of text in text input element

But I see, it works only for input elements :(

<code contenteditable="true" id="editor"  onkeypress="CreateStyle()">
  select * <span style="color:blue">from</span> SomeTable</code>

how can I play with cursor position inside a code tag ?

Ali CAKIL
  • 383
  • 5
  • 21

1 Answers1

1

You can use Range and Selection to set the selection

const codeNode = document.getElementById('editor');
const range = document.createRange();
const selection = window.getSelection();

range.setStartAfter(codeNode.lastChild);
range.setEndAfter(codeNode.lastChild);

selection.removeAllRanges();
selection.addRange(range);
<code contenteditable="true" id="editor"  onkeypress="CreateStyle()">
  select * <span style="color:blue">from</span> SomeTable</code>
AvcS
  • 2,263
  • 11
  • 18
  • This code sends the cursor end, but what if we want to keep current position index, not to end? – Ali CAKIL Jul 08 '19 at 12:37
  • 1
    You could save the position in a variable or element attribute when focus is gone and retrieve it when focus comes back – shrys Jul 08 '19 at 12:46