Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
Javascript selection API to set selectionStart index from zero on every new line

I was learning the Selection API from javascript.info .This is the code i've been working

<textarea id="area" style="width:80%;height:60px">
Selecting in this text updates values below.
Selecting in this text updates values below.
If nothing is selected, or we use equal start and end in setRangeText,
then the new text is just inserted, nothing is removed.
</textarea>
<br>
From <input id="from" disabled> – To <input id="to" disabled>

<script>
  area.onselect = function() {
    from.value = area.selectionStart;
    to.value = area.selectionEnd;
  };
</script>

.We can select any word from the textarea and it'll generate the corresponding index number.

The issue is, the range starts from zero (start of the entire text) and not from a newline. Can i make it so that when i select a word in a newline, it should start from index-0 (start of that line - till the selection)

<textarea id="area" style="width:80%;height:60px">
Selecting in this text updates values below.
Selecting in this text updates values below.
If nothing is selected, or we use equal start and end in setRangeText, then the new text is just inserted, nothing is removed.
</textarea>

In this example, "nothing" is a word in line-3 with index number-1. But in the example pasted here ,"nothing" has index number from 93 - 100. Here we see the index is started from start of that file and not from the start of line 3, i was expecting the word "nothing" in line 3 to have index number-1 and index-0 for the word "if".

I tried splitting the textarea and set area.selectionEnd="\n" thinking now the index will start at zero from next new line. But it does not work.I also know selectionStart=RANGE and area.selectionEnd=RANGE also take range. But not sure how to use it in my situation.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda