views:

339

answers:

2

Hi all,

I am just trying to learn jquery, and I was wondering how can you figure out when, given a bunch of text in a textarea, is the user at the end of textarea and tries to click down. For example, the last line of the text is asdf, and when the user is at that line, and presses down on the arrow key, i would like to get an event of some sort, or at least be able to figure out whether we are at the last line, and do an action (for example, wrap around and go to the first line)

If anyone has some idea of how to do this, it would be greatly appreciated!

Jason

A: 

If you are trying to resize the textarea when the user fills it up, there is a Jquery plugin for it already:

plugins.jquery.com/project/TextAreaResizer

Knix
Thanks a lot! However, it doesn't automatically resize when it fills up, the user have to drag it. I'm basically looking for a way to detect when the user have filled up a textarea, and do something when that happens.
FurtiveFelon
There are character counters that you can use just like the ones you see here when you add comments. When the counter reaches a limit, you can trigger your event.
Knix
Here is an example:http://www.ajaxray.com/blog/2007/11/09/interactive-character-limit-for-textarea-using-jquery/
Knix
A: 

If you are wanting the textarea to expand as the user fills it up you can do something like this:

function resizeTextarea(textarea) {
    var defaultHeight = 150;
    var lines = textarea.val().split("\n");
    var count = lines.length;
    $.each(lines, function() { 
     count += parseInt(this.length / 70); 
    });
    var currHeight = textarea.height();
    var rows = parseInt(currHeight / 20) - 1;

    if (count > rows && currHeight < 600) { // Increase height unless 600 or higher
     textarea.css("height", (currHeight + (defaultHeight/2)));
    }
    else if (((count + 7) <= rows) && (currHeight > defaultHeight) && (count > 5)) { // Decrease height
     textarea.css("height", (currHeight - (defaultHeight/2)));
    }
    else if ((count <= rows) && (count <= 5)) { // If less than 5 rows, use default height
     textarea.css("height", defaultHeight);
    }
}
$('textarea.resizable').each(function() {
    $(this).bind("keypress input beforepaste", function(){
     resizeTextarea(event.target);
    });
    resizeTextarea($(this)); // Initial refresh
});
PetersenDidIt