Dylan Dylan - 1 year ago 89
Javascript Question

JavaScript textarea get numbers of lines (with linebreaks)

I have a textarea and I want to know how many lines there are. Now I have searched but I only see this solution:


Well, that works but that's not what I want.

For example my textarea is like this:


When I type this:


When I use split("\n").value I get 2 which is correct but if I put this in:


I get the result 1 which isn't correct:

textarea without enters

The result should be 2 because there are 2 lines however the line breaks are not created with

Anyone an idea how you can calculate the number of lines INCLUDING the line breaks without

Answer Source

Got it!

static lineCaculator() {
            let dummy               = document.createElement('div');
            dummy.style.font        = AutoTextareaResizer.computedStyle.call(this, 'font');
            dummy.style.width       = AutoTextareaResizer.computedStyle.call(this, 'width');
            dummy.style.wordWrap    = 'break-word';
            dummy.innerHTML         = this.value;


            let lines = parseInt(AutoTextareaResizer.computedStyle.call(dummy, 'height')) /  this.realLineHeight;


            return Math.max(1, lines);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download