30

I was wondering if anybody knows how I would go about detecting when the scrollbar appears inside a textarea.

I am currently using mootools for my JavaScript and I am having issues getting it to detect a scrollbar.

caiosm1005
  • 1,686
  • 1
  • 19
  • 31
Jamie
  • 1,005
  • 5
  • 16
  • 25
  • 1
    Out of curiosity, why would you want to detect it? – falstro Jul 13 '10 at 15:08
  • 1
    because I wanted to use it to detect when 3 lines of text had been placed in a textbox and stop allowing any more characters being entered. – Jamie Jul 13 '10 at 15:35

4 Answers4

43
function has_scrollbar(elem_id)
{
    const elem = document.getElementById(elem_id);
    if (elem.clientHeight < elem.scrollHeight)
        alert("The element has a vertical scrollbar!");
    else
        alert("The element doesn't have a vertical scrollbar.");
}

See this jsFiddle http://jsfiddle.net/qKNXH/

Sunrise
  • 175
  • 1
  • 13
Tommaso Taruffi
  • 8,932
  • 9
  • 44
  • 56
7

I made a jQuery "compatible" version of Tommaso Taruffis code

function resize_until_scrollbar_is_gone(selector) { 
    $.each($(selector), function(i, elem) {
        while (elem.clientHeight < elem.scrollHeight) {
            $(elem).height($(elem).height()+5);
        }
    });
}

It can handle multiple elements and accepts: selectors, jQuery objects, or DOM elements.

It can be called like this:

resize_until_scrollbar_is_gone('textarea');
Community
  • 1
  • 1
powtac
  • 40,542
  • 28
  • 115
  • 170
5

Tommaso's solution works perfectly, even with a text area. But if the user were to type in the textarea and suddenly the textarea gave itself a scrollbar, your javascript wouldn't know or be triggered.So you might want to add something like

 onKeyUp='has_scrollbar("textareaID")'
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
Capt Otis
  • 1,250
  • 1
  • 12
  • 18
-1

For React I've found https://github.com/andreypopp/react-textarea-autosize

import Textarea from 'react-textarea-autosize';
...

<Textarea maxRows={3} />
Alex Kumundzhiev
  • 245
  • 3
  • 10