Joseph Raphael
Joseph Raphael

Reputation: 348

Auto-resize textarea adds too many extra lines

I have a jQuery coded textarea that limit the characters to 11 per line and auto resize depends on the lines.

when clicking enter to add a new line, it adds 2 or 3 more lines (it suppose to add only 1) and the number keeps multiplying as the user clicks on 'Enter'.

$(document).ready(function(){
    var textArea = $('#foo');
    //var maxRows = textArea.attr('rows');
    var maxChars = textArea.attr('cols');
    textArea.keypress(function(e){
        var text = textArea.val();
        var lines = text.split('\n');
       if (e.keyCode == 13){
           //return lines.length < maxRows;
        }
        else{ //Should check for backspace/del/etc.
            var caret = textArea.get(0).selectionStart;
            console.log(caret);
            
            var line = 0;
            var charCount = 0;
            $.each(lines, function(i,e){
                charCount += e.length;
                if (caret <= charCount){
                    line = i;
                    return false;
                }
                //\n count for 1 char;
                charCount += 1;
            });
                   
            var theLine = lines[line];
            return theLine.length < maxChars;
        }
    });
    
});

// Applied globally on all textareas with the "autoExpand" class
$(document)
    .one('focus.autoExpand', 'textarea.autoExpand', function(){
        var savedValue = this.value;
        this.value = '';
        this.baseScrollHeight = this.scrollHeight;
        this.value = savedValue;
    })
    .on('input.autoExpand', 'textarea.autoExpand', function(){
        var minRows = this.getAttribute('data-min-rows')|0, rows;
        this.rows = minRows;
        rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 17);
        this.rows = minRows + rows;
    });
.ta { 
    background-color:#d5d5d5;
    padding:10px;
}

#foo { 
    background: transparent url(http://s24.postimg.org/62v2ipx81/underline.png) repeat; 
    border:none;
    display:block;
    font-size:18px;
    box-sizing: content-box;
    height:auto;
    width:300px;
    overflow:hidden;
    line-height:30px;
    font-weight:bold;
    white-space: nowrap;
    color:black;
    resize: none;
    outline-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ta">
    I like my name because:<br />
<textarea id="foo" class="autoExpand" cols="11" var rows="3" data-min-rows="3"></textarea>
<br />
</div>

The code is in the JSfiddle here

Upvotes: 0

Views: 544

Answers (1)

Frank Cadillac
Frank Cadillac

Reputation: 245

You divide per 17 but line-height is 30

rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 30);

I saw that baseScrollHeight is 89 and the difference increases always by 29

Fiddle here ==> http://jsfiddle.net/qx4qknfb/

Upvotes: 2

Related Questions