Skip to content

Instantly share code, notes, and snippets.

@yiyizym
Last active October 29, 2017 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yiyizym/6e9eb583dafe1d0a335235a3de18157f to your computer and use it in GitHub Desktop.
Save yiyizym/6e9eb583dafe1d0a335235a3de18157f to your computer and use it in GitHub Desktop.
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