views:

140

answers:

2

I have this textarea that shows inputted text, but when the number of lines exceeds the size and width of the textarea, the user has to scroll down to see what they have last inputted.

I'd like the textarea to be set to the bottom everytime the enter button is pressed.

I've tried the following, but I can't get it to work:

function inputKeyDown(evt, input) {    
    if (evt.keyCode == 13) {    
        var textarea = document.getElementById("textarea");  
        textarea.value += "\n" + ">" + " " + input.value;  
        input.value = "";  
        return false;       
    }  
    var elem = document.getElementById('textarea');  
    elem.scrollTop = elem.scrollHeight;    
} 

and then I call the function keyDown in <input onKeyDown="return keyDown(event, this);" ...>

Any idea why no workie?

A: 

Try the following:
textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;

four33
A: 

It depends on what sort of input you are looking at, but forcing the cursor back to the bottom could potentially be a serious usability problem. If you need a textarea that automatically expands, have a look at existing solutions such as this jQuery plugin

I'm not really sure if this is what you want but have a look this: http://jsfiddle.net/yV76p/

var textarea = document.getElementById("textarea");

textarea.onkeyup = function(evt) {
    this.scrollTop = this.scrollHeight;
}
Yi Jiang