Need help with resizing multiple textarea
elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea
, but it does not work when there are multiple textareas
on the page.
Here is the code that works for a single textarea:
If you test this code with one textarea, it will resize appropriately as you type or add new lines.
Can someone please explain why this code fails to work for two or more textareas? How can I modify the code to make it function properly for multiple instances like the following:
$(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;
});
/* JUST FOR THIS DEMO */
html, body {
height: 100%;
}
body {
background: #4A90E2;
display: flex;
align-items: center;
}
textarea {
display: block;
box-sizing: padding-box;
overflow: hidden;
padding: 10px;
width: 250px;
font-size: 14px;
margin: 50px auto;
border-radius: 6px;
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='autoExpand' rows='3'
data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
<textarea class='autoExpand' rows='3'
data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>