Search code examples
javascriptjqueryhtmlfocuscursor-position

How to focus end of the text in <code> tag in HTML using Javascript?


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 ?


Solution

  • 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>