I have a web page at http://form.kr/q/client/caret.php.
The page works like the following.
I like to make it like the following.
Is it possible with your help?
I have a web page at http://form.kr/q/client/caret.php.
The page works like the following.
I like to make it like the following.
Is it possible with your help?
Hi @joon1, first you need to get the line number from the query string analogously to the caret position; then you might split()
the text area value by line breaks, and reduce()
the lines to the sum of their lengths:
const textarea = document.getElementById('say')
function setLinePosition (line) {
// Get the lines up to the desired number
const lines = textarea.value.split('\n').slice(0, line)
// Add the line lengths (+1 to get to the start position of the next line)
const position = lines.reduce((result, line) => result + line.length, 1)
// Set selection start and end to the calculated position
textarea.selectionStart = textarea.selectionEnd = position
}
setLinePosition(2) // -> Cursor will be at position 8
PS: From your code comments I gather you need to support IE; in this case you can’t use const
and arrow functions, so here’s the ES5 version (just in case):
var textarea = document.getElementById('say')
function setLinePosition (line) {
var lines = textarea.value.split('\n').slice(0, line)
var position = lines.reduce(function (result, line) {
return result + line.length
}, 1)
textarea.selectionStart = textarea.selectionEnd = position
}
setLinePosition(2)
I made a page at http://form.kr/q/client/line3.php?line=2 .
It seems not to work. where is my mouse?
Try to focus()
the text area afterwards as in your original code; otherwise the cursor position will change when clicking the text area yourself.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.