You can use these 2 functions written below by Jamie Munro ( setSelectionRange() and setCaretToPos() ):
function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function setCaretToPos (input, pos) { setSelectionRange(input, pos, pos); }
EXAMPLE:
for example, if you want to set the caret at the end of your text area, you can get the following: setCaretToPos(document.getElementById('textarea'), -1);
source share