Text area expands as we place more text
Desired BehaviorI want to have a fixed height text area and when i insert a big text height remains as it is and textarea becomes scrollable
$('#textarea1').val('');
$('#textarea1').bind('input propertychange', function() {
M.textareaAutoResize($('#textarea1'));
});
<textarea id="textarea2" rows="10" cols="50" style="height: 100px;"></textarea>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-field col s12">
<textarea id="textarea1" style="height: 100px;" class="materialize-textarea"></textarea>
<label for="textarea1">Textarea</label>
</div>
The issue presented on the above snipper, what i need is a textarea like the plain one which adds a scroll on big texts.
I got through the documentation and the only mention on textarea's is this
There is any way to make textarea scrollable with custom css or even better through the library alone?advanced note: When dynamically changing the value of a textarea with methods like jQuery's .val(), you must trigger an autoresize on it afterwords because .val() does not automatically trigger the events we've binded to the textarea.
Set the height
of textarea
and override it with !important
. This will ensure that the textarea won't resize. For scrolling part, add rows
and oninput
attribute. oninput
is triggered every time the value of an element changes even while it still is in focus.
Read more: https://html.com/attributes/textarea-onchange/#ixzz5RoZe3nfp
In materialize.css file, in class textarea.materialize-textarea
, you'll find that overflow-y
is set to hidden
. So with the help of rows, lineCount and overflow-y, scrollable materialize textarea with fixed height can be achieved.
HTML -
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" rows="5" oninput="changedValue()"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
</form>
</div>
CSS -
textarea {
height: 8rem !important;
}
JS -
function changedValue() {
let text = document.getElementById("textarea1");
let textValue = text.value;
let row = text.getAttribute('rows');
let lines = textValue.split(/\r|\r\n|\n/);
let count = lines.length;
if (count >= row) {
text.style.overflowY = "scroll";
}
else if (count < row) {
text.style.overflowY = "hidden";
}
}
Credits - Ir Calif - For line count