volume one
volume one

Reputation: 7563

How to override Firefox's element.style but also allow for auto sizing?

I have a couple of textareas on my site. One need to be an initial height of 50px (about 2-3 rows height) and the other an initial height of 25px (a single row). Both use JQuery AutoSize to grow the height of the textareas as more text is added.

If I use the CSS !important rule like this:

textarea-large {
  height: 50px !important;
}
textarea-small {
  height: 25px !important;
}

Then it overrides Firefox's style which is great, but the AutoSize stops working. As I add more text, the textbox stays the same size and I can't read what I've typed.

How do I set an initial height that overrides Firefox's element.style but also allows autosize to work and grow the textarea in height as more text is added?

Upvotes: 1

Views: 172

Answers (1)

user1934286
user1934286

Reputation: 1762

Changing the height to min-height will do the trick.

See this fiddle.

Here is the HTML and CSS for that fiddle:

<textarea class="large"></textarea>
<textarea class="small"></textarea>

textarea { margin: 1em; outline: none; text-align: justify; overflow: hidden; }
.large { min-height: 50px !important; }
.small { min-height: 25px !important; }

Here is the script that I used to make it auto-size:

$(function() {
    //  the following simple make the textbox "Auto-Expand" as it is typed in
    $("textarea").keyup(function(e) {
        //  the following will help the text expand as typing takes place
        while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
            $(this).height($(this).height()+1);
        };
    });
});

Upvotes: 1

Related Questions