Reputation: 2507
I have a textarea with a lot of text in it, and I have code so that when you press Shift+Enter, it will insert a piece of text. However, at the moment, as soon as that happens, the text scrolls so that the carets at the bottom of the screen.
My insert code:
$("#body textarea").bind('keydown', function(event) {
var caret = $("#body textarea").caret();
if(event.keyCode == 13 && event.shiftKey)
{
var text = "[br]"
insertText("#body textarea", caret.start, caret.end, text, "");
$("#body textarea").caret(caret.start+(text.length), caret.start+(text.length));
}
});
Does anyone know what I can do to stop it forcing the caret to the bottom?
Cheers
BlackWraith
Upvotes: 0
Views: 1420
Reputation: 408
I found on stackoverflow.com same trouble and make sample for you http://jsfiddle.net/deerua/WAZBQ/
Upvotes: 2
Reputation: 4032
You can set the Caret Position manually after inserting your text:
See http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/:
function doGetCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
ctrl is your textarea-element.
setCaretPosition(document.getElementById("textarea", 0);
Upvotes: 0