textarea cols

calculate textarea cols and set max rows limit

by Jaak Kütt

HTML

<textarea id="splitLines"></textarea>

CSS

textarea{
     height:100px;
    width:300px;
    border:1px solid #000;
    letter-spacing: 10px;
}

JavaScript

var textarea = document.getElementById("splitLines");

// add a function to doc ready
(function () {
    
    // check if textarea has cols are set
    if (textarea.getAttribute('cols')) {
        return;
    }
    
    // cache prev values
    var rows = textarea.getAttribute('rows'),
        computed = window.getComputedStyle(textarea),
        height = computed.height,
        lineHeight = computed['line-height'],
        fontSize = computed['font-size'],
        newCols = 0,
        val = textarea.value,
        overflow = computed.overflow;
    
    // set temp values
    textarea.setAttribute('rows', 1);
    textarea.style.height = fontSize;
    textarea.style.lineHeight = fontSize;
    textarea.style.overflow = 'auto';
    textarea.removeAttribute('cols');
    
    // set init value
    textarea.value = 'M';
    
    //set height to no scroll with one letter
    while (textarea.clientHeight < textarea.scrollHeight) {
        textarea.style.height = (parseInt(textarea.style.height) + 1) + 'px';
    }    
    
    // calculate cols before we hit scrollbar
    while (textarea.clientHeight >= textarea.scrollHeight) {
        textarea.value += 'M';
        newCols++;
    }
    
    // restore values
    if (rows) {
        textarea.setAttribute('rows', rows);    
    }
    textarea.setAttribute('cols', newCols);
    textarea.value = val;
    textarea.style.height = height;
    textarea.style.lineHeight = lineHeight;
    textarea.style.overflow = overflow;
    
}());

var limit = 3; // <---max no of lines you want in textarea
var spaces = textarea.getAttribute("cols");

textarea.onkeyup = function() {
   var lines = textarea.value.split("\n");
    
   for (var i = 0; i < lines.length; i++) 
   {
         if (lines[i].length <= spaces) continue;
         var j = 0;
         
        var space = spaces;
        
        while (j++ <= spaces) 
        {
           if (lines[i].charAt(j) === " ") space = j;  
        }
    lines[i + 1] = lines[i].substring(space +...