I'm trying to insert some text after a user presses enter in a textarea and position the cursor immediately after the inserted text. There's similar questions addressing the issue of setting the cursor to the desired position (jQuery Set Cursor Position in Text Area), but I already can set the cursor position appropriately.
My question: Is there a way to prevent the cursor position from moving to the beginning of the textbox when the textarea value is altered, before I change the cursor position afterward?
Why I ask: If one presses enter when the textarea is scrolled down, then the textarea scrolls back to the top before resetting the cursor position, which is distracting (the user will see the first contents of the textbox flash on the screen before the textbox scrolls down).
sample code (http://jsfiddle.net/ywNbu/3/)
$('#input').on("keypress", function(e) {
if (e.keyCode == 13) {
e.preventDefault();
var value = $("#input").val();
pos = $("#input").prop('selectionStart');
$("#input").focus();
// following line changes the cursor position to the beginning
$("#input").val(value.substring(0, pos) + "\nHello\n" + value.substring(pos));
this.setSelectionRange(pos + 7, pos+7);
return false;
}
});