I am working on a project where the the total amount of rows in a textarea will be equal to the offsetHeight
of another element divided by 24. When setting the total amount of rows the user cannot create more rows by pressing enter, however when any text that is written overflows the width of the textarea, it will still create a new line.
Since the height of the div that the textarea inherits is resizable, it is also unknown. This means that i cannot implicitly set a character count limit. Since the textarea also gets its height from the other div, i cannot set a fixed height and hide any overflow.
How can i stop the user from creating new rows by typing too much text?
So far i've attempted to limit the amount of lines in the textarea. My program currently does not allow the user to manually create any more lines after reaching the last row by pressing enter, but the user can still create more rows by simply writing more text.
Here is my code:
HTML
<div id="container">
<div id="resizable-div">
<div></div>
</div>
<div class="text-content">
<textarea id="text-area"></textarea>
</div>
</div>
Javascript
let resizeDiv = document.getElementById('resizable-div');
let textArea = document.getElementById('text-area');
function changeHeight(){
if (resizeDiv.offsetHeight % 24 != 0) {
resizeDiv.style.height = `${(Math.round(resizeDiv.offsetHeight / 24) * 24) - 48}px` // Sets height to correspond to line-height and then removes 48px to compensate for paddidng
}
}
resizeDiv.addEventListener('mouseup', (event) => {
changeHeight();
})
textArea.addEventListener("input", function() {
let maxLines = Math.floor(resizeDiv.offsetHeight / 24)
let lines = textArea.value.split("\n")
if (lines.length >= maxLines) {
textArea.value = lines.slice(0, maxLines).join("\n")
event.preventDefault();
}
})
And a codepen: https://codepen.io/pumpchief/pen/WNKgZmm