How to detect when the textarea has more than one line?

Asked

Viewed 92 times

7

I’m doing a chat, and I came across the following problem, my textarea when breaking a line, whether the user press enter or not have enough space and jump to the next line, my textearea does not increase in size when it reaches the limit, which does not even happen in some chat (Like Discord ...). So I thought the following, I put my textarea in a fixed size, when you have another line, I increase my textarea in 20 pixels.

However I came across this problem, as I detect my lines qts textarea is occupied in text?

Just remembering that whoever is typing the text will not necessarily press enter to break the line.

var $area = $(".textarea")

$area.keyup(function() {
  // HOW DETECT?
})
textarea {
  background-color: aliceblue;
  width: 200px;
  height: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="textarea">
</textarea>

  • 4

    I couldn’t think of anything to detect the amount of lines independent of the break ( n) but maybe you could control the size increase by checking if the textarea has a scroll. If it has a scroll larger than its size means you need to increase a line. It would be something like this: if (el.scrollHeight > el.offsetHeight) { el.rows += 1; /* aqui podemos utilizar algum tipo de limite de tamanho */ }. It’s just an idea, suddenly it helps you ;)

  • I thought to do so, the problem is if the user delete, the scroll will not decrease alone.

1 answer

1

Vinicius, I saw a solution to your problem on the following link (https://stackoverflow.com/questions/17772260/textarea-auto-height)

autosize(document.getElementById("note"));
textarea#note {
	width:100%;
	box-sizing:border-box;	
	display:block;
	max-width:100%;
	line-height:1.5;
	padding:15px 15px 30px;
	border-radius:3px;
	border:1px solid #F7E98D;
	font:13px Tahoma, cursive;
	transition:box-shadow 0.5s ease;
	box-shadow:0 4px 6px rgba(0,0,0,0.1);
	font-smoothing:subpixel-antialiased;
	background:linear-gradient(#F9EFAF, #F7E98D);
	background:-o-linear-gradient(#F9EFAF, #F7E98D);
	background:-ms-linear-gradient(#F9EFAF, #F7E98D);
	background:-moz-linear-gradient(#F9EFAF, #F7E98D);
	background:-webkit-linear-gradient(#F9EFAF, #F7E98D);
}
<script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"></script>
<textarea id="note">Texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto.</textarea>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.