Adjust the size of a textarea once text is removed

When you type text, a textarea expands in size. But what if you want it to dynamically decrease its height when deleting text?

$('textarea').on('input', function() {
  var scrollHeight = parseInt($(this).prop('scrollHeight'));
  $(this).height(scrollHeight);
});
.OuterDiv
{
  width:200px;
  height:300px;
  border:1px solid #000;
  position:relative;
  bottom:0;
}
.text
{
  resize:none;
  width:198px;
  height:45px;
  max-height:145px;
  background-color:rgba(90,90,180,1);
  font-size:16px;
  font-family:Arial;
  overflow-y:auto;
  padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
  <textarea class="text" placeholder="Write some text..."></textarea>
</div>

Answer №1

Ensure to set the height style rather than the property, and establish an initial height to consistently begin at 45px.

$('textarea').on('input', function() {
    $(this).css('height', "45px");
    $(this).css('height', this.scrollHeight+"px");
});
.OuterDiv
{
  width:200px;
  height:300px;
  border:1px solid #000;
  position:relative;
  bottom:0;
  }
.text
{
  resize:none;
  width:198px;
  height:45px;
  max-height:145px;
  background-color:rgba(90,90,180,1);
  font-size:16px;
  font-family:Arial;
  overflow-y:auto;
  padding:0;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
  <textarea class="text" placeholder="Enter text here..."></textarea>
</div>

Answer №2

Utilizing a div with the attribute contentEditable will automatically adjust its size based on the content, eliminating the need for any additional scripting:

.ResizableDiv
{
  width:200px;
  height:300px;
  border:1px solid #000;
  position:relative;
  bottom:0;
}
.textArea
{
  resize:none;
  width:198px;
  min-height:45px;
  height:auto;
  max-height:145px;
  background-color:rgba(90,90,180,1);
  font-size:16px;
  font-family:Arial;
  overflow-y:auto;
  padding:0;
}

[contenteditable=true]:empty:before{
  content: attr(placeholder);
  display: block; /* For Firefox */
  color: grey;
}
<div class="ResizableDiv">
  <div class="textArea" contentEditable="true" placeholder="Share your thoughts..."></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

Utilizing Think ORM seamlessly across multiple files without the need to repeatedly establish a connection to the

I'm facing a situation where I have numerous models for thinky, and in each file I am required to create a new object for thinky and connect it multiple times due to the high number of models. var dbconfig = require('../config/config.js')[& ...

Angularfire allows for easy and efficient updating of fields

Currently, I am working on creating a basic lateness tracker using AngularFire. So far, I have successfully added staff members to the miniApp and set the initial late minutes to a value of 0. My challenge lies in updating these values. Ideally, when a us ...

Change justify-content-between to something else

After successfully fixing the issue with aligning the navbar brand in the middle of my navigation bar, I am now facing a new challenge. I want to add a button right before the right navigation toggle, but all my attempts have been unsuccessful so far. I&ap ...

Tips for dynamically adjusting the size of a div container according to the user's

I have been working on a unique landing page design featuring a menu made up of custom hexagons. I aim to make these hexagons dynamically adjust to fill the entire screen based on the user's resolution, eliminating the need for scrolling. For a previ ...

What is the superior choice for PHP scripts that are suitable for real-world projects?

While delving into the world of PHP, I am curious about the best approach for inserting HTML tags within a PHP script. Is it better to use PHP echo statements or to break the PHP script to incorporate HTML with the help of opening and closing PHP tags? B ...

Loading articles seamlessly in Yii using Ajax

I am currently working on a project where I need to display articles from databases, but every time an article is viewed, the whole page reloads. I would like to load articles without having to reload the page, and I believe this can be achieved using Ajax ...

Send the data to the web form along with the JSON information

I find myself in a situation where I am looking for alternative ways to pass data to a redirect page without using querystrings. Here is the current implementation on the Source Page: window.location = "invaliduser.aspx?u=" + encodeURI(username); Consi ...

Reorganizing the layout of grid items

Currently, I am working on a task involving GRID CSS. The main objective of the task is to utilize GRID specifically, rather than other methods like flex. I have successfully set up two columns in my GRID, each with its own divs. However, what I am struggl ...

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...

The combination of Three.js and React

Hello everyone! I am completely new to Three.js and I'm currently attempting to integrate it with React. While looking for resources, I came across this helpful medium article on the topic: Starting with React 16 and Three.js in 5 minutes My goal is ...

Activating the delete event trigger for a tinyMCE object

How can I create a function that activates when a user deletes an object in tinyMCE? I want to remove uploaded images from a cache folder whenever a user deletes an image from the tinyMCE editor. If they upload an image and then delete it, I would like an ...

ES6 Conditional Import and Export: Leveraging the Power of Conditional

Looking to implement a nested if else statement for importing and exporting in ES6? In this scenario, we have 2 files - production.js and development.js which contain keys for development and production code respectively. Additionally, there is another fil ...

Adding a border to the input field in Bootstrap for enhanced styling and visibility

Looking to replicate the border style on an input element as shown in this image: The current code I have is producing a different result. Can anyone assist me in achieving the desired border style? <!DOCTYPE html> <html lang="en"> <head ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Is there a versatile Node.js HTTP request module that is compatible with both server-side and browser-side development, particularly when packaged with Webpack?

Currently, I am searching for a request module that can operate seamlessly in both the Node.js server and the client when compiled with Webpack. The requirements are quite straightforward. I simply need to execute some basic HTTP Ajax requests such as get ...

Transferring data from one HTML element to another using Angular [Ionic]

My project involves utilizing an ionic slide box to display a series of images within it. <ion-slide-box> <!-- I am looping through the images based on the image count --> <ion-slide ng-repeat="n in [].constructor(imageCount) track by $in ...

Node.js setInterval is a method used to repeatedly execute a function

I have a code snippet for an http request that is supposed to run every one minute. However, I am encountering an issue with the following error: "Error: listen EADDRINUSE". Here is my current code: var express = require("express"); var app = express(); v ...

I am experiencing challenges with utilizing moment and angular filters

I was able to get this code working perfectly before the recent jsfiddle update. However, now it seems to be causing issues. Any assistance would be greatly appreciated. Let's start with the HTML code: <div ng-app="app" ng-controller="ctrl"> ...