I have a textarea and when I click in it I want to move the caret to the last character so Something[caret]
function moveCaret(){
// Move caret to the last character
}
<textarea onclick="moveCaret();">
Something
</textarea>
As I know this is somehow possible with the TextRange object, but I don't really know how to use it
EDIT: I would love to see only pure javascript solutions so no libraries please.
The simplest way to move the caret is to click the mouse at the desired location in the text area. The caret can also be moved using the keyboard. The LEFT , RIGHT , UP and DOWN keys move the caret in the respective direction, and the PAGE_UP and PAGE_DOWN keys move the caret up and down one screen-full, respectively.
To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.
You also need the input's selectionDirection to get the caret position whenever selectionDirection is backward i.e. you make a selection left-ward in the textbox so that selectionStart is the caret, but when selectionDirection is forward the caret will be at selectionEnd.
The following function will work in all major browsers, for both textareas and text inputs:
function moveCaretToEnd(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
However, you really shouldn't do this whenever the user clicks on the textarea, since the user will not be able to move the caret with the mouse. Instead, do it when the textarea receives focus. There is also a problem in Chrome, which can be worked around as follows:
Full example: http://www.jsfiddle.net/ghAB9/3/
HTML:
<textarea id="test">Something</textarea>
Script:
var textarea = document.getElementById("test");
textarea.onfocus = function() {
moveCaretToEnd(textarea);
// Work around Chrome's little problem
window.setTimeout(function() {
moveCaretToEnd(textarea);
}, 1);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With