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?!
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.