A guide to using JavaScript to restrict the textarea's height while allowing it to expand dynamically and setting a maximum height

Seeking assistance with a challenge I have encountered and unsure how to resolve. Any help would be greatly appreciated!

The issue at hand is as follows:

I am currently working on a textarea. My goal is to have the input box start with a height of 36px, but as text is inputted, the height of the box should expand to 72px. However, the maximum height should be capped at 72px and not increase further with additional text input.

The above is what I am aiming to achieve. As I am still new to programming, I am unsure if this can be accomplished through CSS alone or if JavaScript is required. How can I fulfill this requirement using JavaScript?

Thank you to everyone who takes the time to read my question and offer assistance. Your help is much appreciated.

Code Snippet:


        body {
          min-height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        ... (remaining CSS code)
      
    

        <div class="demo">
          <div class="wrap">
            <ul class="tool">
              <li>photo</li>
              <li>file</li>
              <li>example</li>
            </ul>
            <textarea class="chat"></textarea>
            <div class="tool__footer">
              <input type="checkbox" id="enter"><label for="enter">ENTER</label>
              <a type="text" class="send" href="javascript:;">send</a>
            </div>
          </div>
        </div>
      
    

https://i.sstatic.net/FMlkX.png

Answer №1

An easy fix by counting the number of line breaks:

function adjustTextareaHeight(value) {
  let linebreaks = (value.match(/\n/g) || []).length-1
  // calculate height based on line breaks
  let height = 36 + (linebreaks * 20)
  return height;
}

let textarea = document.querySelector(".chat");
textarea.addEventListener("input", () => {
  let height = adjustTextareaHeight(textarea.value);
  // Set minimum height to 36px
  if (height<36){
  textarea.style.height = '36px'
  } else {
   // Cap height at 72px
    textarea.style.height = height >72 ?"72px" :height + "px";
  }
});
.chat{
height:36px;
/* Add transition for smooth resizing */
transition:all 0.2s;
}
<!-- Use wrap="off" for rows=newlines behavior -->
<textarea wrap="off" class="chat"></textarea>

Answer №2

Solution

A simple oninput event handler can be used to resize the textarea dynamically with every new input. This technique was inspired by a solution from .

<textarea class="chat" oninput="this.style.height = ''; this.style.height = Math.min(this.scrollHeight - 4, 72) + 'px'"></textarea>

Explanation

Each time a new input is provided, the height of the textarea is set to the minimum value between its scrollHeight (the space needed to display the entire content) and 72 pixels. It is essential to account for the padding when calculating the new height, as scrollHeight includes the padding of the textarea while the height does not. The usual padding for textareas is 2 pixels (total 4 pixels for top and bottom), hence the need to adjust by 4 pixels with this.scrollHeight - 4. For a different padding value, the subtraction should be adjusted accordingly.

Your example

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.demo {
  width: 100%;
  padding: 16px;
  border: 1px solid #222;
  box-sizing: border-box;
}
.demo .tool {
  display: flex;
  list-style-type:none;
}
.demo .tool li {
  padding: 16px;
  background-color: #ccc;
  border: 1px solid #222;
}
.demo .chat {
  margin-top: 16px;
  width: 100%;
  height: 36px;
}
.demo .tool__footer {
  margin: 16px;
}
.demo .tool__footer .send {
  text-decoration: none;
  padding: 8px;
  background-color: #f9cf5a;
  color: #222;
  border-radius: 6px;
}
<div class="demo">
  <div class="wrap">
     <ul class="tool">
        <li>photo</li>
        <li>file</li>
        <li>example</li>
     </ul>
    <textarea class="chat" oninput="this.style.height = ''; this.style.height = Math.min(this.scrollHeight - 4, 72) + 'px'"></textarea>
    <div class="tool__footer">
       <input type="checkbox" id="enter"><label for="enter">ENTER</label>
       <a type="text" class="send" href="javascript:;">send</a>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a JSON array from a C# collection can be achieved by utilizing the System.Web.Script.Serialization

Can someone help me with this code snippet? var httpWebRequestAuthentication = (HttpWebRequest)WebRequest.Create("http://api"); httpWebRequestAuthentication.ContentType = "application/json"; httpWebRequestAuthentication.Accept ...

What is the best way to efficiently transmit Objects through AJAX utilizing bodyParser in node.js express?

Currently attempting to execute: $.ajax({ type:"POST", url:"/psychos", data:JSON.stringify(this.psycho) }) Upon reaching the server, I encounter the following: app.post("/psychos", function(request, respon ...

Tips for aligning content at the bottom center of a design

Could you assist me in positioning the buttons at the bottom center of the horizontal layout as depicted in the image below? Ps: the vertical layout at the top has a dynamic height. My HTML code is as follows: <html> <body> <div class="c ...

Challenge with NodeJS, Angular Seed, Gulp, Jasmine, and Karma

Starting an Angular Seed project and everything was working fine. I managed to launch the Jasmine browser, but encountered issues with my specs not working. In an attempt to fix this, I added a karma.conf file, which unfortunately broke the Jasmine browser ...

Exploring the Depths of JSON Arrays within Typescript

I am faced with a challenge in extracting the value of the "id" from the following array of JSON data. The issue lies in the fact that the value is enclosed within double square brackets "[[" which are causing complications in retrieving the desired result ...

What is the functionality of {all: initial} and how does it address issues with default values?

Why do paragraphs inherit properties like line-height and text-align from the div element? If values for these properties are: normal -> for line-height [i.e. font-size = 16px (initial / default value) * normal (value is usually around 1.2 -> 19.2 ...

Add an error message to my throw object within the JSON response

I need to include the error message from the JSON Response of the API in my error object {'status': response.status, 'msg': ''} if there is one, or else just throw the error object without a message. However, currently the thr ...

Utilize Jquery to extract HTML content from an array of links and implement regular expressions

Currently, I am embarking on the journey of developing a Google Chrome extension despite my limited experience in this field. My aim is to create a tool that can identify individuals who have left reviews on Amazon products. Specifically, I am looking to l ...

A quirky bug with Tumblr's JS/Jquery Infinite Scroll and Masonry feature

As someone new to JS/JQuery and masonry, I seem to be facing a puzzling issue with overlapping posts/divs. Despite my extensive search for answers, I have run out of ideas. The problem arises from the content at this link: Below is the complete theme cod ...

Is there a way to make a row stand out when it's clicked on

I have a data table with rows that I want to be able to highlight when clicked. The issue I'm facing is that the checkbox within each row is triggering the highlight event when clicked. How can I ensure that clicking on the checkbox only checks it wit ...

Error: The Stripe webhook payload must be submitted as either a string or a Buffer

I'm currently working on setting up a subscription system using Stripe. I have mostly followed the code from their documentation, but I keep encountering the following error: Webhook signature verification failed. Webhook payload must be provided as a ...

Error encountered in amCharts Serial Chart when data parsing is enabled with the setting "parseDates": true which resulted in the failure to display data

Using Spring as a webservice, I received a JSON response with stock data: [ { "date": "2016-04-17", "open": 1085.0, "high": 1092.2, "low": 1072.0, "close": 1088.3, "volume": 54100, "value": 1088.3 }, { "date": "2016-04-14", "open": 1081. ...

ways to animate the closing of a dropdown menu

I'm currently working on a navbar dropdown animation code that works on hover. However, I've encountered an issue when trying to use it on a phone - I can open the dropdown, but I can't seem to close it. Does anyone have suggestions on how ...

The div element is overflowing beyond the available space

I have already searched for a solution to this question, but despite trying everything, I have not been able to find one. Therefore, I am asking again, my apologies :-). My challenge is to make a row fill all the remaining screen space on the page, but no ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

Error message encountered on localhost: preflight response contains Access-Control-Allow-Headers issue

I'm currently working on my React app locally at localhost:3000 and utilizing this code snippet: try { const response = await fetch('https://myendpoint.com/abcd/search?c=abc123', { headers: { 'Content-Type': 'application ...

The challenges of updating AngularJS partial templates and handling refresh in 2-way binding

I've encountered an issue with a partial template that's loaded outside of my ng-view, complete with its own controller. Here's a breakdown. Basic template layout <html ng-app="myApp"> ... <div ng-include src="'myPartia ...

AngularJS can be used to display a webpage

After facing the need to print a given page using AngularJS, I came up with a simple solution as shown below: <div class="modal fade" id="extrait" aria-hidden="true" data-backdrop="false"> <table class="table table-hover table-bordered" i ...

Is it possible for the useUser() function within the Auth0 nextjs-auth0 library to retrieve user information without relying on cookie data?

The useUser() method by Auth0 is designed to retrieve information about a logged-in user by calling the /api/auth/me endpoint. This triggers the handleAuth() function, which sets up Auth0 (creating a sessionCache instance, etc.) and calls profileHandler(re ...

Error: The object 'require' is not recognized in Vue Component

I am facing an issue while using screenfull.js (import screenfull from "screenfull") in a Vue component. Can anyone help me with this problem? Here is the error information. Version: Vue: 2.6.14 @vue/cli-service: 5.0.4 Babel-loader: 8.2.5 Vue-loader: ...