Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!