📜 ⬆️ ⬇️

Dynamically changing text entry field. Is it possible?

Task:
Make a comment input field (textarea) on the form so that its size (height) is changed according to the number (lines) of the text.
The user can enter a couple of words on a single line or insert a table twenty lines high from Excel - the input field should automatically increase / decrease.
The length of the lines is different (the form is rubber and depends on the size of the browser window), the lines can be transferred either along the \ r \ n or simply, if they do not fit in the width.
In principle, we need a formula for counting the number of lines of text in order to change the rows attribute of textarea.

Javascript is welcome. If the solution is possible only by means of html / css, then even better.

Solutions:
For IE, the ingenious solution was suggested by kosiasik :
in textarea style register overflow: visible

The universal solution suggested drJonnie :
the textarea sets the height in pixels and hangs the event on pressing any key (including the mouse). This event each time compares scrollHeight and clientHeight; if the first is greater, then the height of the textarea is updated.

I almost implemented this solution:
  function adjustHeight (textarea) {
     var dif = textarea.scrollHeight - textarea.clientHeight
     if (dif) {
         if (isNaN (parseInt (textarea.style.height))) {
             textarea.style.height = textarea.scrollHeight + "px"
         } else {
             textarea.style.height = parseInt (textarea.style.height) + dif + "px"
         }
     }
 } 
it remains to hang it on the events onFocus, onBlur, onKeyPress, etc., by choice
drJonnie brought his decision below in the comments
lahmatiy gave a solution using jQuery ( use case ), but I didn’t want to connect the whole framework for the sake of a single function
I thank all the participants in the discussion.

')

Source: https://habr.com/ru/post/21905/


All Articles