Expanding and Shrinking Text Areas with Jquery

I am looking to create a textarea that comes preloaded with content. The height of the textarea should adjust to auto when there is content present, but switch to a height of 4.2rem when it is empty. Additionally, I want the textarea to dynamically increase and decrease in height as text is entered, with a maximum height of 7.7rem using jQuery.

Any suggestions on how to achieve this?

.textAreaGrow {
  padding: 1.8rem 0 .8rem;
  height: 4.2rem;
  max-height: 7.7rem;
}
<textarea class="textAreaGrow">Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</textarea>

Answer №1

To dynamically adjust the height of a textarea based on user input, you can set the height to the scrollHeight of the element whenever text is added to the textarea.

An additional if statement can be included to check if the textarea is empty. If it is empty, the height can be set to its default height.

$(document).ready(function() {
  let txtArea = $('.textAreaGrow');
  txtArea.on('input', updateHeight);

  function updateHeight() {
    let t = txtArea;
    if (t.val().trim() == "") {
      t.css('height', '4.2em');
    } else {
      t.css('height', '0.1px');
      t.css('height', t[0].scrollHeight);
    }
  }
  updateHeight();
})
.textAreaGrow {
  height: 4.2rem;
  max-height: 7.7rem;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="textAreaGrow">Preloaded text

With newlines too??</textarea>

Answer №2

In certain scenarios, it might be beneficial to opt for a different HTML element instead of the textarea. You could use an element with the attribute contenteditable to have more control over the styles. However, this approach may not provide all the functionalities of a form element like textarea. The choice between the two would ultimately depend on the intended purpose of the element.

.textAreaGrow {
  border: thin gray solid;
  padding: 1.8rem 0 .8rem;
  width: 20em;
  min-height: 4.2rem;
  max-height: 7.7rem;
  overflow: scroll;
}
<div class="textAreaGrow" contenteditable>
  Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic, or web designs.
</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

How can JavaScript be used to automatically send a user to a designated page based on a selected option in

I am in the process of creating a JavaScript function that redirects users based on their selection from a dropdown menu. Additionally, I need to ensure that the word "admin" is set for both the username and password fields. view image here function my ...

NodeJS application does not acknowledge the term "Require"

I have completed the steps outlined on http://expressjs.com/en/starter/installing.html to set up my express NodeJS application. Following the installation, we navigated to the "myapp" directory and installed the "aws-iot-device-sdk" from https://github.com ...

The div element moves to the right as soon as the drop-down menu pops up

Currently, I am facing an issue with aligning an image inside a div that is centered in an outer-wrapper. The outer-wrapper contains a horizontal menu at the top with 5 sub divs displayed inline. I have implemented CSS for a drop-down menu that appears whe ...

An issue arises when attempting to send form information through email using PHP

I'm facing an issue with sending email from a form. Every time I submit the form, I receive an "error occurred" message as specified in my if else statement. This prevents the mail from being sent. Can you help me troubleshoot this problem? Below is t ...

Calculating Three.js world coordinates based on mouse position using an orthographic camera

This question may have been asked before and answered, but despite following several suggestions (such as the one found here Mouse / Canvas X, Y to Three.js World X, Y, Z), I am still facing difficulties with my current situation. I have successfully impl ...

What is the best method for incorporating success icons into my website with vue.js?

Hey everyone, please excuse my lack of expertise as I am a beginner in this field. I'm trying to incorporate success icons into my website using bootstrap or similar tools, but I'm unsure of how to implement the if statement below. If anyone co ...

Redux repeatedly triggers re-rendering despite the absence of any changes in the state

This is my first venture into React-Redux projects. I was under the impression that React only re-renders when a component's state changes. However, I am currently facing confusion. The component is being re-rendered every 1 to 3 seconds even thoug ...

Implement a mandatory parameter in the URL route using ui-router

My Angular routing configuration using ui-router is quite simple: $stateProvider .state("master", { abstract: true, url: "/{tenantName}" }) .state("master.home", { url: "", }) .state("master.login ...

Removing Click event upon button click - Implementing Vue and Vuetify

In my project using Vuetify, I have implemented a dialog that opens when a button is clicked. The dialog can be closed after completing the required actions. However, in the production environment, the dialog cannot be reopened more than once due to the re ...

Can CSS be used to separate elements within a div from the overall page styles, similar to how an iFrame functions?

Is there a way to isolate elements within a div, similar to how it would behave in an iFrame? I am facing issues with the global SharePoint styles affecting my app inside SharePoint. I want to completely disable these global styles so that my app only use ...

Active bootstrap navigation tabs

I am struggling to maintain the active tab in my left navigation tab. The issue arises when I load the page with the first tab active, and then click on another tab - the new tab becomes active, but the first tab remains active as well. I would like only t ...

Oops! There seems to be an issue with an invalid character in the literal true value while making a POST request to the API with JSON data. The expected character should be

Can anyone help me solve an issue I am facing while trying to use the POST method to insert data using JSON in JS code? When I attempt the transformation, I receive an error message stating: "ERROR: invalid character ' ' in literal true (e ...

Ajax response values overlap

I am developing an application that requires multiple Ajax requests, but I encountered a problem where I am receiving the same response values for both requests. Each request must include a data field called activityCode, yet I keep getting the value of Sc ...

The jQuery preloader remains stuck, failing to transition to the main page

I'm struggling to figure out where the problem lies as there are no errors in the console. The page is stuck on the loading screen and won't redirect to the actual site. Here's the HTML code for the preloader: <!--preloader--> &l ...

What is the best way to send the accurate data type from PHP to Javascript?

My approach involves using the jQuery post method to insert a record in MySQL. The issue I'm facing is that when comparing the output of the PHP using ==, all three conditionals function correctly. However, with ===, the first two conditionals return ...

Why is the startsWith function not returning the expected result in my code? What could be causing this issue?

I have a code snippet that sorts a list based on user input, but it fails if the user's input contains spaces. How can I modify the code to handle inputs with spaces without removing the spaces between characters? For example, if the user input is &ap ...

Transform a text with HTML tags into sentences while preserving the separators in Javascript

Here is a unique string with some embedded HTML code: This is the first sentence. In the second sentence, there is a <a href="http://google.com">Google</a> link! The third sentence may have an image like <img src="http://link.to.image.com/h ...

Chrome is the only browser displaying background images

My current issue is that the background image only appears on Chrome and not on Firefox or Edge. I am trying to have a different background image each time the page loads. $(document).ready(function() { var totalBGs = 5; var rnd = Math.floor(Math.ran ...

Ways to retrieve JSON objects from the Controller using ajax

Currently, I am developing a mail validation controller using jQuery AJAX and PHP. Once the message is validated in the PHP controller, I attempt to retrieve it using AJAX and display it on the screen using jQuery. Here is an excerpt of my AJAX code: .. ...

Using MongoDB in a feathers.js Hook

I'm struggling to make a feathers.js hook wait for a MongoDB call to complete before proceeding. I've tried using returns and promises, but so far nothing has worked. How can I ensure the hook waits for the database query to finish? ...