0

I need one help. I need to fix the the textarea height as per the content written inside it. I am explaining my code below.

<html>
  <head>
    <link rel="stylesheet" href="lib/style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="lib/script.js"></script>
  </head>

  <body>
    <h1>Hello</h1>
    <textarea id="textarea-container">
    Line 1
    Line 2
    Line 3
    Line 4
    ccccccccccccccccccccc
</textarea>
<script>
  var $textArea = $("#textarea-container");

// Re-size to fit initial content.
resizeTextArea($textArea);

// Remove this binding if you don't want to re-size on typing.
$textArea.off("keyup.textarea").on("keyup.textarea", function() {
    resizeTextArea($(this));
});

function resizeTextArea($element) {
    $element.height($element[0].scrollHeight);
}
</script>
  </body>
</html>

Here some text are present inside the textarea and its scrolling. I need here the text area height will expand as per the content present inside it not more than that and it never scroll.

  • https://www.impressivewebs.com/demo-files/textarea-auto-resize/ if the above link is showing exactly what you wanted. here is the link for full code. https://www.impressivewebs.com/textarea-auto-resize/ Thanks – Chandu May 03 '18 at 10:11

1 Answers1

0

I've created a simplified example. It gets scrollHeight property of textarea element and sets inner height according to it. overflow-y: hidden is important because otherwise scrollHeight property is calculated together with a vertical scrollbar.

// Set height after page has loaded
adjustTextAreaHeight($('#textarea-container'));

// Attach keydown event
$('#textarea-container').on('keydown', adjustTextAreaHeight);

function adjustTextAreaHeight(ta) {
  if (!ta.length) {
    ta = $(this);
  }
  // Get full scroll height of text area element
  var scrollHeight = ta.prop('scrollHeight');
  // Some browsers do not shrink element, so we set 0 height at first
  ta.innerHeight(0)
    .innerHeight(scrollHeight);
}
#textarea-container {
  overflow-y: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<h1>Hello</h1>
<textarea id="textarea-container">
    Line 1
    Line 2
    Line 3
    Line 4
    ccccccccccccccccccccc
</textarea>
Vaidas
  • 1,494
  • 14
  • 21