Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
How to move the cursor to the end of the currently active line within a textarea?

We have a textarea and want to set the cursor to the end of the currently active line where the cursor is situated.

Example content within the textarea:

This is our first line,
then comes a second line,
followed by a third line which holds *|* the cursor
and a fourth line.

Now the blinking cursor *|* should end up after the word cursor after execution of the javascript function.

What would be the javascript code to do this?


Some initial Ideas:

To get the line number this code can be used:

let line_number = textarea.value.substr(0, textarea.selectionStart).split("\n").length;

To go over all lines of the textarea:

let lines = textarea.value.split("\n");

Get length of current line:

let end_of_line = lines[line_number-1].length;

Then:

// set the cursor position to the end of the line
textarea.selectionStart = end_of_line;

Seems not to work...

Do we have to count all chars until the current line and then add the line length to it - this as the new cursor position?!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is the solution I came up with:

// line where cursor is now
let line_number = textarea.value.substr(0, textarea.selectionStart).split("\n").length;

// split all lines of the textarea
let contentlines = textarea.value.split("\n");

let charcount = 0;

for (var i=0; i < line_number-1; i++)
{
    // count line break as one char
    charcount += contentlines[i].length + 1;
}

let end_of_line = contentlines[line_number-1].length;

textarea.selectionStart = charcount+end_of_line;
textarea.selectionEnd = charcount+end_of_line;

No guarantee that it is 100 % correct and works in all cases.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda