7

The duplicate suggested is the question where I got the basis for this question, so it is not a duplicate! As a matter of fact, I already have linked to that question from the start...


GOOD EDIT:

I made a JSFiddle ( my first time :) ). Notice how the textarea does not expand as one would wish. Type something inside the textarea and it will get resized immediately.

If we can automatically send a keypress event, it may work... (this relevant question did not help, the answers had no effect).


I am using the textarea as is from here. Then, I read from a file and I am putting the content inside the textbox, but it doesn't get resized as it should.

I update the textbox like this:

function updateTextbox(text) {
  $('#cagetextbox').val(text);
};

Any ideas?

I am on firefox 34.0 canonical, at Ubuntu 12.04, if that plays some role, which I hope is not the case, since some of my users use Chrome.


EDIT:

An attempt would be to write something like this:

$('#cagetextbox').attr("rows", how many rows does the new text contain);

Note that if we try to find out how many lines of text the textarea contains, we will get 1 as an answer.


EDIT_2

Maybe something like width/(length_of_line * font_size). For a few tests, it seems to be correct, if I subtracted 1 (by keeping only the integer part of the result of course).

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • it's typically best to make it as big as will fit using ,say, `width: 100%;`, and letting the text fill and scroll as needed, rather than risk an over-sized box in the viewport. – dandavis Apr 28 '15 at 21:34
  • I would like to keep it resizeable for various reasons @dandavis, but thanks for the comment. – gsamaras Apr 28 '15 at 21:35
  • well, it's hard to tell the pixel size the font will use (subject to zoom, user-prefs, OS, os-text-size, etc), which means that the `cols=n` is the only reliable way to size it up. so then you need to find the width of the longest line, and set the `cols` attrib to that.`cagetextbox.cols=Math.max.apply(null, text.split("\n").map(function(a){return a.length;}));` – dandavis Apr 28 '15 at 21:38
  • @dandavis what you posted doesn't work even with my latest attempt, but we are close. See my edit! – gsamaras Apr 28 '15 at 21:55
  • 1
    I ran into this on a project with the same concerns about OS, fonts, zoom, etc. I created a div out of view onto the dom with the same CSS rules as the element the user was using. I added the text, measured it, applied its height and width to the other element the user was using, and then destroyed the temporary div. In that case it was for a WYSIWG for an editor app, but the principle is the same. – Radio Apr 28 '15 at 23:08
  • We had built a WYSIWG editor too! :) @Radio, on this specific case of mine, do you know what I have to do? I haven't touched web development for ages, so if I can't find any solution here, then I will drop the feature with no support for resizing. – gsamaras Apr 29 '15 at 09:24
  • @Radio how did you measure the text? That's what I can't find it! – gsamaras Apr 30 '15 at 10:49
  • You could measure the width of the text with a canvas 2D context. – Evan Knowles Apr 30 '15 at 11:11
  • possible duplicate of [Auto expand a textarea using jQuery](http://stackoverflow.com/questions/2948230/auto-expand-a-textarea-using-jquery) – Evan Knowles Apr 30 '15 at 11:15
  • @G.Samaras see my answer below. – Radio Apr 30 '15 at 15:00

3 Answers3

6

Your textArea didn't update the height itself even when you trigger the 'input.textarea' on it because this value is undefined:

this.baseScrollHeight

It's only defined after a 'focus' on the textarea.

I have modified your code a little bit: http://jsfiddle.net/n1c41ejb/4/

so, on 'input'

    $(document).on('input.textarea', '.autoExpand', function(){
        var minRows = this.getAttribute('data-min-rows')|0,
            rows;
        this.rows = minRows;
        this.baseScrollHeight = this.baseScrollHeight | calcBaseScrollHeight(this);
        rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
        this.rows = minRows + rows;
    });

and move the baseScrollHeight calculation to a separate function

function calcBaseScrollHeight(textArea) {
    var savedValue = textArea.value,
        baseScrollHeight;
    textArea.value = '';
    baseScrollHeight = textArea.scrollHeight;
    textArea.value = savedValue;
    return baseScrollHeight;
}

then call your updateTextBox like this:

$('#cagetextbox').val(text).trigger('input.textarea');
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Mr. Duc Nguyen
  • 1,049
  • 7
  • 16
  • I subtracted 1 from `this.rows = minRows + rows;` and seems very good! The Cage players would like to thank you too (we play there, google cage samaras for more). – gsamaras Apr 30 '15 at 14:01
  • Notice that it worked like a charm when I replaced in the `html` part the two 3 with two 1. – gsamaras Apr 30 '15 at 14:09
1

You can use the following code to adjust the height of an element, in your case a textarea. While it does use a loop, it avoids several display and scrolling problems that way.

function autoheight(a) {
    if (!$(a).prop('scrollTop')) {
        do {
            var b = $(a).prop('scrollHeight');
            var h = $(a).height();
            $(a).height(h - 5);
        }
        while (b && (b != $(a).prop('scrollHeight')));
    };
    $(a).height($(a).prop('scrollHeight'));
}

Resize on any events you like.

$("#cagetextbox").on("keyup change", function (e) {
    autoheight(this);
});

And/or when events are not triggered automatically call it yourself.

function updateTextbox(text) {
    $('#cagetextbox').val(text);
    autoheight($("#cagetextbox"));
};

Fiddle

Thaylon
  • 453
  • 5
  • 12
  • The Cage players thank you very much (we play there, google cage samaras for more). – gsamaras Apr 30 '15 at 13:41
  • However, this ruins the nice resizing that was talking place before that. Nevertheless, good effort! – gsamaras Apr 30 '15 at 14:02
  • Im sorry, which resizing is ruined? Also, try entering text in the middle or the beginning of the textarea in the fiddle to this answer and in the one to the other answer, at least in chrome the cursor position isnt preseved in the other fiddle. – Thaylon Apr 30 '15 at 14:38
1

I created a working fiddle. It creates an input textfield exactly as if it were displayed in the non editable div.

https://jsfiddle.net/khgk7nt5/2/

Example CSS

.test{
    font-family:"Times New Roman", Times, serif;
    font-color:#CCCCCC;
    font-size:20px;
    width:300px;
}
.testLoc{
    position:absolute;
    top:-1000px;
}

JavaScript

var testText = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore"

var test = $("<div/>");
test.addClass("test testLoc");
test.text(testText);
$("body").append(test);

var out = $("<textarea/>");
out.addClass("test");
out.width(test.width());
out.height(test.height());
out.val(testText);
$("body").append(out);
test.remove();
Radio
  • 2,810
  • 1
  • 21
  • 43