Skip to content

Instantly share code, notes, and snippets.

@djsubstance
Created February 1, 2023 00:16
Show Gist options
  • Save djsubstance/453529e989a5489777e685f354bddd7d to your computer and use it in GitHub Desktop.
Save djsubstance/453529e989a5489777e685f354bddd7d to your computer and use it in GitHub Desktop.
BEST Textarea auto-expand
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea' autofocus></textarea>
function getScrollHeight(elm){
var savedValue = elm.value
elm.value = ''
elm._baseScrollHeight = elm.scrollHeight
elm.value = savedValue
}
function onExpandableTextareaInput({ target:elm }){
// make sure the input event originated from a textarea and it's desired to be auto-expandable
if( !elm.classList.contains('autoExpand') || !elm.nodeName == 'TEXTAREA' ) return
var minRows = elm.getAttribute('data-min-rows')|0, rows;
!elm._baseScrollHeight && getScrollHeight(elm)
elm.rows = minRows
rows = Math.ceil((elm.scrollHeight - elm._baseScrollHeight) / 16)
elm.rows = minRows + rows
}
// global delegated event listener
document.addEventListener('input', onExpandableTextareaInput)
// OLD SOLUTION USING JQUERY:
// // 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) / 16);
// this.rows = minRows + rows;
// });
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
/* JUST FOR THIS DEMO */
html,body{ height:100%; }
body{ background:#000; display:flex; align-items:center; }
textarea{
display: block;
box-shadow: 20px 20px 50px 15px grey;
box-sizing: padding-box;
overflow: hidden;
background: #44455579;
color: lightcyan;
padding: 10px;
width: 250px;
font-size: 18px;
margin: 50px auto;
border-radius: 6px;
box-shadow: 2px 2px 8px rgba(black, .3);
border: 0;
&:focus{
border: none;
outline: none;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment