EN
JavaScript - how to make textarea autogrow?
3
points
Using JavaScript it is possible to make textarea
element autogrowing in following way.
1. Scroll height detection examples
Approach presented in this ection uses following fact: when height
is set as auto
we are able to get scrollHeight
equal to content height that can be used to set as current textarea
height
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<textarea style="resize: none;" id="my-element">Type multi-line text here</textarea>
<script>
function preapreAutogrowing(element) {
function onAction() {
var style = element.style;
style.height = 'auto';
style.height = element.scrollHeight + 'px';
}
element.addEventListener('input', onAction);
element.addEventListener('change', onAction);
var destroyed = false;
var result = {
update: onAction,
destroy: function()
{
if (destroyed)
return;
destroyed = true;
hElement.removeEventListener('input', onAction);
hElement.removeEventListener('change', onAction);
}
};
return result;
}
var element = document.querySelector('#my-element');
var autogrowing = preapreAutogrowing(element);
element.value = '1\n2\n3\n4\n5\n6';
autogrowing.update();
</script>
</body>
</html>
2. Number of lines detection example
Notes:
- this approach does not work if word wrapping is enabled
- in different browsers effect can be different (Firefox and Chrome interpret number of rows different way when horisontal scroll is visible)
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
textarea {
overflow-y: hidden;
white-space: pre;
resize: none;
}
</style>
<script>
function preapreAutogrowing(element) {
var expression = /\n/g;
function onAction() {
var text = element.value;
if(text) {
var match = text.match(expression);
if(match) {
element.rows = match.length + 2;
return;
}
}
element.rows = 2;
}
element.addEventListener('input', onAction);
element.addEventListener('change', onAction);
var destroyed = false;
var result = {
update: onAction,
destroy: function()
{
if (destroyed)
return;
destroyed = true;
hElement.removeEventListener('input', onAction);
hElement.removeEventListener('change', onAction);
}
};
return result;
}
</script>
</head>
<body>
<textarea id="my-element">Type multi-line text here...</textarea>
<script>
var element = document.querySelector('#my-element');
var autogrowing = preapreAutogrowing(element);
element.value = '1\n2\n3\n4\n5\n6';
autogrowing.update();
</script>
</body>
</html>