Borislav Hadzhiev
Last updated: Jan 8, 2022
Check out my new book
To set the cursor at the end of a textarea:
setSelectionRange()
method to set the current text selection
position to the end of the textarea.focus()
method on the textarea element.focus
method will move the cursor to the end of the element's value.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <textarea id="message" rows="5" cols="30">Initial text here</textarea> <button id="btn">Move cursor to beginning</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const textarea = document.getElementById('message'); const end = textarea.value.length; // ✅ Move focus to End of textarea textarea.setSelectionRange(end, end); textarea.focus(); // ✅ Move focus to End of textarea on button click const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { // 👇️ get length right before clicking button const end = textarea.value.length; textarea.setSelectionRange(end, end); textarea.focus(); });
We used the
setSelectionRange
to set the start and end positions of the current text selection in the
textarea
element.
The two parameters we passed to the setSelectionRange
method are:
selectionStart
- a zero-based index of the first selected character.selectionEnd
- a zero-based index of the character after the last selected
character.An index greater than the length of the textarea's value points to the end of the value.
The last step is to call the focus() method on the element.
The focus
element moves the cursor to the element the method was called on.
To set the cursor at the end of a textarea when a button is clicked:
click
event listener to a button element.setSelectionRange()
method on the
textarea element.focus()
method to move the cursor to the end of the textarea.const textarea = document.getElementById('message'); // ✅ Move focus to End of textarea on button click const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { const end = textarea.value.length; textarea.setSelectionRange(end, end); textarea.focus(); });
Every time the button is clicked, the handleClick
function is invoked, where
we:
length
of the value of the element right when the button is clicked. This ensures that the value in the end
variable will always be up to date.