Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page.

Here is the code that works for a single textarea:

If you test this code with one textarea, it will resize appropriately as you type or add new lines.

Can someone please explain why this code fails to work for two or more textareas? How can I modify the code to make it function properly for multiple instances like the following:

 $(document)
    .one('focus.autoExpand', 'textarea.autoExpand', function(){
        var savedValue = this.value;
        this.value = '';
        this.baseScrollHeight = this.scrollHeight;
        this.value = savedValue;
    })
    .on('input.autoExpand', 'textarea.autoExpand', function(){
        var minRows = this.getAttribute('data-min-rows')|0, rows;
        this.rows = minRows;
        rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
        this.rows = minRows + rows;
    });
    /* JUST FOR THIS DEMO */
    html, body {
      height: 100%;
    }
    
    body {
      background: #4A90E2;
      display: flex;
      align-items: center;
    }

    textarea {
      display: block;
      box-sizing: padding-box;
      overflow: hidden;
      padding: 10px;
      width: 250px;
      font-size: 14px;
      margin: 50px auto;
      border-radius: 6px;
      box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
      border: 0;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='autoExpand' rows='3' 
  data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
<textarea class='autoExpand' rows='3' 
  data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>

Answer №1

Modified the one to on, and implemented logic to prevent the repeated initialization of the same element.

$(document)
  .on('focus.autoExpand', 'textarea.autoExpand', function() {
    if (!this.getAttribute('data-initialized')){
      this.setAttribute('data-initialized', 'true');
      var savedValue = this.value;
      this.value = '';
      this.baseScrollHeight = this.scrollHeight;
      this.value = savedValue;
    }
  })
  .on('input.autoExpand', 'textarea.autoExpand', function() {
    var minRows = this.getAttribute('data-min-rows') | 0,
      rows;
    this.rows = minRows;
    rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
    this.rows = minRows + rows;
  });

Answer №2

I made some adjustments to the code in order to utilize a data attribute to keep track of whether or not the box has been initialized. The focus code will only be executed if it hasn't been initialized yet and the data attribute is set.

$(document)
.on('focus.autoExpand', 'textarea.autoExpand', function(){
    if(!$(this).data('initialized')){
      var savedValue = this.value;
      this.value = '';
      this.baseScrollHeight = this.scrollHeight;
      this.value = savedValue;
      $(this).data('initialized', true);
    }
})
.on('input.autoExpand', 'textarea.autoExpand', function(){
    var minRows = this.getAttribute('data-min-rows')|0, rows;
    this.rows = minRows;
    rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
    this.rows = minRows + rows;
});

https://jsfiddle.net/cdga7hkb/1/

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

What is the best way to apply a :visited selector specifically to the most recently visited webpage?

I've noticed that all the pages I've visited on the site have now changed to the color I chose. However, my goal is for only the last page I viewed to be in the color I assigned. Thank you! ...

How should one go about creating an npm package out of a vuejs component and testing it locally?

Initially, I created a vuejs project as a test container using vue-cli. Next, I developed an npm package named "vue-npm-example" from a Vuejs component in my local environment and then imported it into the aforementioned testing project. Within the packag ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title. Below is the JavaScript code: var phonecatApp = angular.module('myApp', []) phonecatApp.controller('myContr ...

Assign a CSS class to a specific option within a SelectField in a WTForms form

Could someone explain the process of assigning a CSS class to the choices values? I am looking to customize the background of each choice with a small image. How can this be done using wtforms and CSS? class RegisterForm(Form): username = TextField( ...

Looking to test form submissions in React using Jest and Enzyme? Keep running into the error "Cannot read property 'preventDefault' of undefined"?

Currently, I am developing a test to validate whether the error Notification component is displayed when the login form is submitted without any data. describe('User signin', () => { it('should fail if no credentials are provided&apos ...

Working with AngularJS: Implementing a Service in a Controller

A service has been developed in AngularJS, but it is not being utilized in the controller. Service.js var appService = angular.module("appService", []); appService.service("bddService", function() { var bdds = bdd; this.getBdds = function(){ ...

Updating the image source through ajax by retrieving the location from the database

Is there a way to dynamically change the image source using AJAX? I have the location saved in my database and I want to set the img src from the value of something like data[0]['patient_photo']. Below is the HTML code for the image: <img id= ...

What could be causing ngInfiniteScroll to not work properly with tables?

I've been attempting to incorporate ngInfiniteScroll into my table using ng-repeat on <tbody> however, it isn't triggering when I reach the end of the page. <div infinite-scroll="list.getMoreItems()"> <table md-table md-row-se ...

React component that enables radio inputs to repeat upon selection

My current project involves creating a quiz app where users can answer single questions using React on Codepen. I am utilizing an API to fetch a question, along with 3 incorrect answers and 1 correct answer, then storing them in the app's state. Howev ...

What could be the reason for the GET method being executed after the DELETE method in ExpressJS?

Whenever I trigger the DELETE method in my Express app, it seems that the GET method is automatically invoked right after. This results in an error within my Angular code stating that it expects an object but receives an array instead. Why is the GET meth ...

Leveraging the power of JavaScript functions together with the asp:Timer component

<p><b> Progress: <asp:Label ID="progressPercentageLabel" runat="server"></asp:Label>%</b></p> <script> function updateBar() { var bar = document.getElementById("CompletionBar"); ...

ReactJS encountered an error of type ERR_INVALID_ARG_TYPE

Hello there! I recently purchased a template from ThemeForest and everything was working perfectly with the previous version. However, upon updating to the new version, I encountered an error that looks like this: > TypeError [ERR_INVALID_ARG_TYPE]: Th ...

AngularJS: Transitioning from Expressions to Javascript (Coffeescript)

Looking to convert an expression into JavaScript in order to maintain an object's value in $scope: <dl class = "mortgage-information"> <dt><abbr title = "Loan-to-value Ratio">LTV</abbr></dt> <dd>{{(total_fi ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

The Angular @HostListener beforeunload Event is a powerful way to handle

I've implemented the following code snippet in my main app.component.ts file within my Angular 17 project: @HostListener("window:beforeunload", ["$event"]) onTabClose($event: BeforeUnloadEvent) { $event.preventDefault(); ...

Avoid the need for users to manually input dates in the Custom Date Picker

After referencing this custom Date picker in ExtJs with only month and year field, I successfully implemented it. However, I am facing an issue where manual entry into the date field is not disabled. My goal is to restrict input for that field solely thr ...

Harvest information using BeautifulSoup and Python

Exploring the world of web scraping with BeautifulSoup in Python, I am interested in extracting the package name and price of each app from the Android Play Store. For retrieving the package name, I implemented the following code : url = "https://play.go ...

What is the best way to arrange images in a 3 by 3 grid, beginning at position 0, using JavaScript to control navigation through button clicks?

When I click on button 1, it starts at image 1 because the counter is set to 0. Clicking on button 2 takes me to image 4 with a counter value of 3, while clicking on button 3 leads to image 7 with a counter value of 6. The process should also work in reve ...