0

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

Connor Deckers
  • 2,447
  • 4
  • 26
  • 45

2 Answers2

2

I found on stackoverflow.com same trouble and make sample for you http://jsfiddle.net/deerua/WAZBQ/

Community
  • 1
  • 1
deerua
  • 408
  • 2
  • 9
  • However, just as a note, I was hoping for a jquery answer, this is more javascript than jquery... just sayin. Thanks though, it'll still do what I want :) – Connor Deckers Feb 08 '12 at 00:35
0

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);
knub
  • 3,892
  • 8
  • 38
  • 63