13

I've got a textarea with a fixed height. When the user types text into the textarea a scrollbar will show up after the user typed some text in it.

How can I get the scrollbar height using jQuery or plain JavaScript? I've been searching for this for hours, but couldn't find anything. I can't just insert a div and get the scrollbar height via the div offset because a textarea is not allowed to have child elements.

Please don't give me a link to a jQuery Plug-In that does the job. I want to learn something.

iWeb
  • 233
  • 1
  • 3
  • 8
  • What browser? FF 4.0, FF 3.6, IE. TextAreas are rendered slightly different in each browser. – John Hartsock May 12 '11 at 15:12
  • Chrome 10 and FF4. I've made sure the textarea has a scrollbar! (not that much height but lots of text in the textarea) – iWeb May 12 '11 at 15:22

3 Answers3

18
textarea.scrollHeight

returns an integer (pixels)

VMAtm
  • 27,943
  • 17
  • 79
  • 125
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • `alert($('textarea:first').scrollHeight);` returns undefined. The selector works fine (I tried it with .css) and jQuery is included. – iWeb May 12 '11 at 15:19
  • 18
    `scrollHeight` is an attribute of the DOM element. It doesn't exist for the jQuery object. Use `.attr('scrollHeight')` or `$('textarea:first').get(0).scrollHeight` – Michal May 12 '11 at 16:15
  • 7
    If using jQuery 1.6 or later, use `$('textarea:first').prop('scrollHeight)` instead of `.attr('scrollHeight)`. "As of jQuery 1.6, [the .prop() method](http://api.jquery.com/prop/) provides a way to explicitly retrieve property values, while .attr() retrieves attributes… Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr." – gfullam Jun 04 '15 at 04:07
2
$.each($("textarea"), function () {
    var scrollHeight = parseInt(this.scrollHeight);
    if ($("this").val() != "" && isNaN(scrollHeight) == false && scrollHeight > 0 && scrollHeight > $(this).height()) {
        console.log($(this).attr("id"));
        $(this).height(scrollHeight);
    }
});
Iurii Tkachenko
  • 3,106
  • 29
  • 34
0

Please note that you should exclude the upper padding and the lower padding of the textarea while comparing the scrollHeight.

Example

var scrollHeight = $("#textarea_id")[0].scrollHeight;
var padding = 14; //upperpadding 7 and lower padding 7.

if($("#textarea_id")[0].height() < (scrollHeight - padding)) {
  $("#textarea_id")[0].height(scrollHeight - padding);
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
Akash gupta
  • 316
  • 4
  • 4