N
N
Nur-Magomed2014-05-01 19:45:52
JavaScript
Nur-Magomed, 2014-05-01 19:45:52

How to put the cursor at the end of the text (Javascript)?

There is an html element:

<div contenteditable="true" class="test">Некоторый текст</div>

The user can type text there, a JS code hangs on the timer, which, during the printing process, replaces some characters entered by users. The problem is that after each replacement, the text input cursor is placed in front of the text and you have to manually rearrange it to the end.
JavaScript code:
var list = document.getElementsByClassName('test'); 

function msgUpd(){
  for(i=0;i<list.length;i++){
    var rep = list[i].innerText.replace('Заменяемый текст','Замена');
    if(list[i].innerText != rep){
      list[i].innerText = rep;
      console.log('Replaced');
    }		
  }
}

setInterval(msgUpd,500);

How to move the cursor to the end of the text using JavaScript, provided that something cannot be changed in html (html is on someone else's site, but this is an extension for the site)?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Eugene Obrezkov, 2014-05-02
@ghaiklor

For the lazy, I'll just throw the qwer code here :)

var input = document.querySelector("input");
input.focus();
input.selectionStart = input.value.length;

And yes, this code only works with input and other input elements.
In your case, you will have to replace it with input, because contenteditable is a little different and has its own atmosphere)

A
Anton, 2014-05-01
@sHinE

As far as I know, the cursor is placed by setting the selection to zero length. Those. look for how to select part of the text in the input field.

V
Vladlen Grachev, 2014-05-01
@gwer

Actually, here .

P
personaljs, 2014-05-02
@personaljs

make it on the input change event and you will not have to bother and everything will be replaced during the input process and not by timeout Example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question