When a textarea contains a new line, it will automatically add an additional row and expand the size of the textarea

Developed a form with the functionality to move placeholders in a textarea upwards when clicked. The goal is to increment the height of the textarea by 1 row for every line break. However, I am uncertain about what to include in the if statement of my JavaScript function to verify the presence of a line break:

//function SetNewSize(textarea) {
//    if (textarea.value.length > 106) {
//        textarea.cols += 1;
//        textarea.rows += 1;
//    } else {
//        textarea.cols = 2;
//        textarea.rows = 2;
//    }
//}

function SetNewSize(textarea) {
  if (textarea.rows > 1) {
    textarea.rows += 1;
  } else {
    textarea.rows = 2;
  }
}
*,
*:before,
*:after {
  box-sizing: border-box;
}

body {
  width: 100%;
  min-height: 300px;
}

form {
  width: 600px;
  margin: 2em auto;
  font-family: 'Source Sans Pro', sans-serif;
  font-weight: 300;
  font-size: 22px;
}

form legend {
  font-size: 2em;
  margin-bottom: 1em;
  width: 100%;
  border-bottom: 1px solid #ddd;
}

.float-label .control {
  float: left;
  position: relative;
  width: 100%;
  border-bottom: 1px solid #ddd;
  padding-top: 23px;
  padding-bottom: 10px;
}

/* More CSS styles here */

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml>

<head runat="server">
  <title></title>
</head>

<body>
  <form class="float-label" spellcheck="false">
    <legend>Float Label Demo</legend>
    <!-- more HTML code here -->
  </form>
</body>

</html>

Answer №1

You can calculate the number of line breaks using the split function, by splitting on \n..

To prevent the scrollbar flicker, simply add overflow-y: hidden to the textarea since we are increasing its size.

Edit: Another approach could be to adjust the height of the element instead of altering rows. The required height can be obtained from textarea.scrollHeight..

For example:

function SetNewSize(textarea) {
   textarea.style.height = "0px";
   textarea.style.height = textarea.scrollHeight + "px";
}
*,
    *:before,
    *:after {
      box-sizing: border-box;
    }
    body {
      width: 100%;
      min-height: 300px;
    }
    form {
      width: 600px;
      margin: 2em auto;
      font-family: 'Source Sans Pro', sans-serif;
      font-weight: 300;
      font-size: 22px;
    }
    form legend {
      font-size: 2em;
      margin-bottom: 1em;
      width: 100%;
      border-bottom: 1px solid #ddd;
    }
    .float-label .control {
      float: left;
      position: relative;
      width: 100%;
      border-bottom: 1px solid #ddd;
      padding-top: 23px;
      padding-bottom: 10px;
    }
    .float-label .control.small {
      width: 30%;
      border-right: 1px solid #ddd;
    }
    .float-label .control.medium {
      width: 70%;
      padding-left: 10px;
    }
    .float-label .control:last-child {
      border: 0;
    }
    .float-label input,
    .float-label textarea {
      display: block;
      width: 100%;
      border: 0;
      outline: 0;
      resize: none;
    }
    .float-label input + label,
    .float-label textarea + label {
      position: absolute;
      top: 10px;
      transition: top 0.7s ease, opacity 0.7s ease;
      opacity: 0;
      font-size: 13px;
      font-weight: 600;
      color: #ccc;
    }
    .float-label input:valid + label,
    .float-label textarea:valid + label {
      opacity: 1;
      top: 3px;
    }
    .float-label input:focus + label,
    .float-label textarea:focus + label {
      color: #2c8efe;
    }


    textarea {
      overflow-y: hidden;
    }
<!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form class="float-label" spellcheck="false">
      <legend>Float Label Demo</legend>
      <!-- we need a wrapping element for positioning the label -->
      <!-- the required attribute is ... required! -->
      <div class="control" contenteditable>
        <textarea name="description" id="myTextArea" onKeyUp="SetNewSize(this);"  placeholder="Description" required></textarea>
        <label for="title">Title</label>
      </div>
      <div class="control" >
        <textarea name="description" placeholder="Description"  required onKeyUp="SetNewSize(this);" ></textarea>
        <label for="price">Price</label>
      </div>
      <div class="control">
        <textarea name="description" placeholder="Description"  required onKeyUp="SetNewSize(this);" ></textarea>
        <label for="description">Description</label>
      </div>
    </form>
    </body>
    </html>

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

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

Send information using AJAX within a .NET integrated browser

In our current setup, we utilize a .NET embedded browser to showcase an HTML page that is generated by applying an XSLT file to an XML file using .NET. This process results in HTML content displayed within the embedded browser through the DocumentText prop ...

The Semantic-UI Dropdown does not appear when utilizing the sidebar feature

Is it normal for a dropdown in the pusher not to show when using a sidebar? I tried setting overflow-visible but it didn't work. Any suggestions on how to resolve this? Check out this JSFiddle example: https://jsfiddle.net/3djmjhn5/1/ Code: $(&ap ...

Is there a way to dynamically load a file on scroll using JavaScript specifically on the element <ngx-monaco-diff-editor>?

I've been attempting this task for over a week now in Angular without success. Would someone be able to provide guidance? The onContainerScroll() function isn't being triggered, and I'm considering using JavaScript instead. How can I achiev ...

When using Ajax in Jquery and expecting data of type JSON, the response always seems

Looking to create a basic jQuery Ajax script that checks a user's discount code when the "Check Discount Code" button is clicked? Check out this prototype: <script> jQuery(function($) { $("#btn-check-discount").click(function() { c ...

Having trouble displaying a dynamically created table using jQuery

I'm a newcomer to jQuery and I need help with querying 2 web services. The goal is to query the first service, use an attribute value to query the second one, and then populate a table with data from both services. Please take a look at my code on th ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

Handling CORS in Vue.js applications

As a newcomer to Vue, I am currently grappling with a CORS issue in my application. During development at http://localhost:8080/, sending a request to , I was able to resolve the CORS problem using the following code snippet: vue.config.js module.exports ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

Learn how to showcase the value of the selected radio button in AngularJS

To show the chosen radio button in the response div, make sure to hide the div if no option is selected. Check out the code below: <body ng-app="QuestionDisplayModule"> <form> <div ng-controller="QuestionDisplayController" ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...

Switch up the styling of a component by updating its properties with a switch statement

Although there is a similar question, my query has a unique requirement. I have defined the common styles for my button and implemented a function using a switch statement with different properties for various buttons across different pages. However, for ...

What is the best way to retrieve data from within a for loop in javascript?

Seeking assistance in Typescript (javascript) to ensure that the code inside the for loop completes execution before returning I have a text box where users input strings, and I'm searching for numbers following '#'. I've created a fun ...

Problem with Ajax functionality on Jquery Dialog

I have implemented a Jquery.dialog feature in my application for sending messages. When the user clicks on "new", the dialog box appears, allowing them to select the recipient (currently working with IDs instead of usernames). On the first opening of the ...

How to implement a Datapicker plugin in jQuery version 2.1.1?

After discovering a datepicker plugin designed for JQuery version 1.1.1, I encountered compatibility issues with my current version of 2.1.1. Does anyone know if there is a datepicker plugin available specifically for jQuery 2.1.1? ...

After removing an item from the array, React fails to display the updated render

As a newcomer, I am struggling with a particular issue. I have implemented a delete button for each item in a list. When the button is clicked, the object in the firstItems array is successfully deleted (as confirmed by logging the array to the console), b ...

Is there a way to extract the MIME type from a base64 string?

My base64 String appears as "UklGRkAdEQBXQVZFZm10IBIAAAABAAEAg...". I am attempting to download this file using my browser. Therefore, I convert it to a blob with the following function: b65toBlob: function(b64Data, sliceSize = 512) { ...

What is the best way to display a 'confirmed' message on my registration page once a user has submitted their information?

I have set up a nodejs server and developed a registration page using HTML. When users click the submit button, the server I built receives the input data and validates it. If the user is successfully added to the database, I want to display a new message ...

Issue with React when attempting to add a secondary class to Toggle component

Is there a way to add a second class to my <div> with the class "button"? When I try to append 'toggle-button', the class doesn't seem to work. <CSSTransitionGroup transitionName="buttonAninmated" transitionEnterTimeout={30 ...