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

New update in Next.js version 13.4 brings a modification to routing system

I'm currently working with Next.js 13.4 and an app directory. I'm trying to implement a centrally located loader that will show whenever there is a route change anywhere within the app. Since routes/navigation don't have event listeners, I&a ...

using java to invoke a server-side function within a mapReduce operation in mongodb

i have saved two functions in the "system.js" collection under the names "mapfun" and "reducefun" and now i am attempting to invoke these functions from Java. I am trying to utilize MapReduceCommand for this purpose but encountering difficulties in calling ...

Tips for dynamically adjusting an iframe's content size as the browser window is resized

Currently, I am in the process of building a website that will showcase a location on a map (not Google Maps). To achieve this, I have utilized an iframe to contain the map and my goal is for the map to adjust its width based on the width of the browser wi ...

What is the best way to horizontally align an inline div using CSS?

Is it possible to apply CSS to center an inline div that has an unknown width? Note: The width of the div cannot be specified beforehand. ...

Is there a way to send multiple actions to Node.js via a dropdown list using POST method?

I have encountered an issue where I am trying to include multiple actions in a single form within a dropdown list. However, I am only able to POST one action at a time. admin.html <form action="/start" method="post" id="tableForm"> <select id= ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

Should pages be indexed to index.php or should the top and bottom parts of the page be created and included in all content pages?

I've been out of the webpage creation game for a while, but I've recently decided to get back into it. Like everyone else, I want to learn the best way to do this. However, I find myself facing a dilemma on how to structure my pages. My initial i ...

What steps can I take to address the issue of missing modules in an Angular application?

I am facing an issue with my Angular application where I am using two local libraries. Despite having all dependencies declared and imported correctly, the build process continues to throw errors related to missing modules. To give you a better picture of ...

Ways to eliminate extra spacing when search bar is expanded

My code is all contained within a header with the class 'example'. When the 'search' button is clicked, a div with the class 'search-bar' appears and its borders match those of the header. However, I want the search bar to ali ...

Issue with the select element in Material UI v1

I could really use some assistance =) Currently, I'm utilizing Material UI V1 beta to populate data into a DropDown menu. The WS (Web Service) I have implemented seems to be functioning correctly as I can see the first option from my Web Service in t ...

Having trouble retrieving AJAX response with jQuery in Laravel 5.3

Currently, I am working on a project in Laravel. I have a form data and a file that needs to be submitted with Ajax to the database. The submission process is working as expected but no response is being returned in the success method. Here is the snippet ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

CSS for a Dropdown Menu with Multiple Layers

I've successfully implemented a dropdown menu, but now I'm facing the challenge of adding another level to it. Specifically, I want a second level to drop down when hovering over "Test3". What do I need to add or modify in the code to achieve thi ...

"multer's single file upload functionality is not functioning properly, but the array upload

Currently, I am facing an issue while using react js to upload a single file. Interestingly, the multer.single() method seems to fail, whereas the multer.array() method works perfectly fine. What could be causing this problem? //Node.js const upload = mult ...

Ways to resolve the error message "Uncaught TypeError: props.options.map is not a function occurring when using a dropdown select

While working on my project, I encountered a strange error with the react select dropdown. Despite following suggestions online to pass an array of objects as options, I'm still facing the same issue. Surprisingly, when I directly input the data fetch ...

Displaying a column value in an alert message using jQuery

I have created a basic table using the table tag along with tr and td tags Within the table, there are 5 rows with columns labeled as empID, empName, and Button1 In the final column of each row, there is a button. When this button is clicked, I want an ale ...

What steps should I take to ensure that this 3D transformation functions properly in Internet Explorer 10?

I'm struggling to get a CSS 3D transform to function properly in IE10. The issue arises because IE10 lacks support for the preserve-3d property. According to Microsoft, there is a workaround available. They suggest applying the transform(s) of the pa ...

Using Node.js to instantly redirect users to a new page while also sending them important

I am currently working on building a basic server for HTML pages using Node.js. The issue I am facing is that when I go to (for instance) http://localhost:8080/someDirectory, the browser mistakenly treats someDirectory as a file (when in reality, it is int ...

Step-by-step guide on sending a JSON object to a web API using Ajax

I have created a form on my website with various fields for user entry and an option to upload a file. After the user fills out the form, my JavaScript function converts the inputs into a JSON file. I am attempting to send this generated JSON data along wi ...

Step-by-step guide for dynamically including dropdown options

Is there a way to dynamically add a dropdown using JavaScript? I currently have a dropdown with numbers that creates another dropdown when selected. However, I want to add the dynamic dropdown through JavaScript. How can I achieve this? Below is the PHP ...