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

Tips for setting a value in $scope within an ng-repeat loop in AngularJS

I'm currently facing an issue with ng-repeat in angularJS, specifically on how to assign a value in $scope inside ng-repeat. Here is my scenario: I have a JSON file that contains all the data structured like this: [ {BookID:1,Chapter:1,ContentID:1, ...

Prevent redirection in JavaScript

My current script is designed to detect an Android device and then redirect the user to "android.html". Once on the "android.html" page, the user has the option to either download an app or click "CONTINUE" to proceed to "index.html". However, there seems ...

Tag utilizing jQuery

Check out my JSFiddle. I'm looking to change the h2 name to a hashtag and update it when the next button is clicked. Does anyone have a solution for this? ...

The loader fails to disappear even after the AJAX response has been received

I am currently working on a page that utilizes AJAX to display data. While the data is being fetched, I want to show a loading animation, and once the data has been retrieved, I want the loader to disappear. Below is a snippet of the code where I am attemp ...

Why is it that the z-index doesn't seem to affect the stacking order of my background image?

I am facing an issue with my Bootstrap carousel where the z-index is not working as expected. The decoration I have in the background is overlapping the text instead of appearing behind it. I want the illustration to be positioned under the text. .carou ...

The form embedded within the <tr> element seems to be malfunctioning

Hey there, I'm facing a little issue with my form that is nested inside a table content. It seems to not be working properly. Let me share the code snippet below: <table> <form name='editpo' method=POST action='js_buat_po.php? ...

Ensure that the jQuery Knob is set to submit any modifications only after the final adjustment

Utilizing jQuery Knob by anthonyterrien, I have configured the step to be 20. My goal is to transmit the knob's value to the server. The issue arises when the change function is triggered every time the user adjusts the knob using either a right or le ...

Modifying the page header content using JavaScript

There's this snippet of code that alters the image on another page: <div class="imgbx"> <button onclick="window.location.href='index.html?image=images/xr-black.jpg&tit=XR-black'" >Invisible ...

Execute code after selecting the link

To simplify my question, I will provide an example: Suppose I have two sample pages that I want to demonstrate: Page 01 <script> var demo = 'X1'; alert(demo); $( document ).ready(function() { $("#cont").on("click" ...

Separating Angular JS controller and Factory into individual files allows for easier organization and

As someone new to web development and Angular, I recently created a module, factory, and controller all in the same file (app.js). Below is an example of the code: //Main Module var ipCharts = angular.module('ipCharts', []); //Factory ipCharts. ...

"Need help on Tumblr: how can I make a div container wrap around a photo

Check out this website. Is there a way to make the div snugly wrap around the image? Currently, it seems to be sticking 4px below the image (as indicated by the red line I added in the background of the div). I'm puzzled as to where those additional ...

Stop zombie.js from loading exclusively third-party resources

During a test, I am using zombie.js to load a page from a local express server. However, the page contains a script element that makes a call to Google Analytics. I want to prevent this external script from loading while allowing other local scripts to run ...

Shorten the text in a flex container using ellipsis and flex-grow

I have a "table" built using flex and I need to truncate the text in the first column if there isn't enough space, keeping it on a single line all the time. .parent { display: flex; border: 1px solid black; gap: 10px; } .first-column { bor ...

Activate fancybox after the AJAX content has finished loading

I have a <div> element with the id <div id="displayinformation"> where I am loading content dynamically using Ajax. Some of the loaded content contains links, and I want to display them in a Fancybox lightbox. I have confirmed that the Fancyb ...

The number range filter in ng-table is malfunctioning

what I am trying to accomplish My goal is to create a column that can accommodate two numbers in order to filter numeric data within a specific range for that column. While sorting, pagination, and filtering by 'contain text' are working correct ...

When there are spaces in the button, it will result in the button creating a new line within the Navbar

There is a line break in the navbar when a space is added to the button text The CSS for the Navbar is manually inputted (Utilizes Bootstrap) <img src="images/SCP_Logo.jpg" style='width: 100%; max-width:100%;'> & ...

Learn the process of extracting data from dynamically generated elements in JavaScript

I am a beginner in Javascript and Jquery and have recently started exploring business rules with Chris Powers. https://github.com/chrisjpowers/business-rules My current project involves adding a range slider for numbers and a number spinner. I attempted us ...

Included adaptable background-images in the upload

Recently, I developed a RoR based app/website that allows clients to upload their own background image to the cover page. Although the current setup works well with a single image, I am aiming to enhance the site's responsiveness by enabling clients t ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...