Is there anyway through CSS or Javascript set the height of the textarea based on the content? I have a hardcoded height in my CSS but i wanted it to default so there is no
Tested in chrome
Pure javascript solution (No plugin, No jquery)
in action: fiddle
I created 3 functions:
//attach input event
document.getElementById('ta').addEventListener('input', autoHeight, false);
function autoHeight(e){
var lh = getLineHeightInPixels(e.target);
var nol = getNumberOfLines(e.target);
var ht = lh * nol;
e.target.style.height = ht + 'px';
}
function getNumberOfLines(el){
var text = el.value
var lines = text.split(/\r|\r\n|\n/);
return lines.length;
}
function getLineHeightInPixels(el){
var tempDiv = document.createElement('div');
tempDiv.style.visibility = 'hidden';
tempDiv.style.fontFamily = getComputedStyle(el).getPropertyValue('font-family');
tempDiv.style.fontSize = getComputedStyle(el).getPropertyValue('font-size');
tempDiv.style.lineHeight = getComputedStyle(el).getPropertyValue('line-height');
tempDiv.style.fontVariant = getComputedStyle(el).getPropertyValue('font-variant');
tempDiv.style.fontStyle = getComputedStyle(el).getPropertyValue('font-style');
tempDiv.innerText = 'abcdefghijklmnopqrstuwxyz';
document.documentElement.appendChild(tempDiv);
var ht = parseInt(getComputedStyle(tempDiv).getPropertyValue('height'))
document.documentElement.removeChild(tempDiv);
return (ht);
}
//set height on document load
document.addEventListener('DOMContentLoaded', function(){document.getElementById('ta').style.height = getLineHeightInPixels(document.getElementById('ta')) + 'px';}, false);