Instantly share code, notes, and snippets.

Embed
What would you like to do?
textarea_auto_height
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<style>
textarea{
padding: 5px;
font-size: 14px;
height: 14px;
line-height: 1;
}
textarea.multilines{
line-height: 1.2;
}
</style>
</head>
<body>
<div id="container">
<textarea></textarea>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
var textarea = document.querySelector('textarea');
var maxLineCount = 5;
function getStyleValue(el, name){
return Number(window.getComputedStyle(el)[name].replace('px',''));
}
function getVerticalPadding(){
return getStyleValue(textarea,'paddingTop') + getStyleValue(textarea,'paddingBottom')
}
function getScrollHeight(){
return textarea.scrollHeight;
}
function getLineHeight(){
return getStyleValue(textarea, 'lineHeight');
}
function isMultilines(){
return getScrollHeight() > getVerticalPadding() + getLineHeight();
}
function shouldShowScrollBar(){
return getScrollHeight() > maxLineCount * getLineHeight();
}
textarea.addEventListener('input', function(){
this.style.height = '0';
this.classList.toggle('multilines', isMultilines());
if(shouldShowScrollBar()){
this.style.height = maxLineCount * getLineHeight() + 'px';
this.style.overflowY = 'scorll';
} else {
this.style.height = getScrollHeight() - getVerticalPadding() + 'px';
}
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment