Can HTML text areas be designed to adjust their width automatically, as well as their height?

Among the numerous StackOverflow examples showcasing an auto-height Textarea, one noteworthy example can be found here:

<textarea oninput="auto_grow(this)"></textarea>

textarea {
    resize: none;
    overflow: hidden;
    min-height: 50px;
    max-height: 100px;
}

function auto_grow(element) {
    element.style.height = "auto";
    element.style.height = (element.scrollHeight)+"px";
}

I am curious if there exists a similar solution that encompasses auto-width functionality in addition to auto-height?

Upon attempting to retrieve element.scrollWidth, I noticed it kept returning the original width of the text area.

https://jsfiddle.net/on7zasd3/


EDIT:

After some experimentation, it seems like I may have cracked the code. (Although I am puzzled as to why the code formatting appears broken beyond this point on StackOverflow?)

  1. I found it necessary to specify cols="1" for the text area

  2. I also had to execute

    element.style.width = "auto";
    and set the texture's width accordingly before initiating the auto height adjustment.

  3. The Textarea also requires CSS property white-space: nowrap;:

    function auto_grow(element) { element.style.width = "auto"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";

     element.style.height = "auto";
     console.log(element.scrollHeight+", "+element.scrollWidth)
     element.style.height = (element.scrollHeight)+"px";
    

    }

    textarea { resize: none; overflow: hidden; min-height: 30px; min-width: 30px; white-space: nowrap; }

Answer №1

It seems like I finally cracked the code.

  1. To get it working, I had to explicitly define cols="1" in the text area

  2. I also needed to execute

    element.style.width = "auto";
    and assign the width of the element before setting the height to auto.

  3. The textarea CSS rule must include white-space: nowrap;

    function auto_grow(element) { element.style.width = "auto"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";

     element.style.height = "auto";
     console.log(element.scrollHeight+", "+element.scrollWidth)
     element.style.height = (element.scrollHeight)+"px";
    

    }

    textarea { resize: none; overflow: hidden; min-height: 30px; min-width: 30px; white-space: nowrap; }

https://jsfiddle.net/on7zasd3/3/

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

Verify if the currentRoute begins with a specific text pattern (such as something/something/*...) in Angular

I need to prevent a loader from appearing on certain screens, so I used ngIf on routes where the loader is not necessary. Here's the code snippet from app.component.ts : <router-outlet> <app-spinner></app-spinner> <ngx-ui-load ...

Update the objects with new values when the user makes changes in the

I am working with dynamically created input fields const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data {navtive?.map((item, index) => { return ( <input type="text" name={item.id} ...

jQuery ajax doesn't function properly on the server, it only works locally

When I send a jQuery Ajax request from my front-end to the back-end to retrieve values for calculations, it works perfectly on my local web server. However, when I try it online, all I get is a result of 0 in my calculations, indicating that the Ajax respo ...

nextJS does not recognize the term 'Window'

I'm encountering the error "window is not defined" in my NextJS project. The variable isMobile determines whether the window size is less than 767.98 to handle the hamburger menu functionality. This code worked in ReactJS but seems to be causing issue ...

Problematic Angular 6 Lazy Loading Situation

Below is the code snippet I am using for lazy loading: const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'manager', lo ...

Pair each element with an array of objects and add them to a fresh array

Let's consider an array of objects like, const attachmentData = [{name: 'Suman Baidh',attachment: ["123","456"]}, {name: 'John Sigma',attachment: ["789","101112]}, ...

Something went awry when I tried to divide the HTML and CSS code

<div class="col-md-12" style=""> <div class="col-md-4 linkdetail" class="cursor"> <div class="col-md-12" style="margin-bottom:40px"> <img src="/img/product3.png" style="display:inline-block;width:100%;"> </div ...

Would this be considered a practical method for showcasing an image with jQuery?

Is there a more efficient way to display an image once it has been loaded using this code? LightBoxNamespace.SetupLightBox = function(path, lightBox) { // Create a new image. var image = new Image(); // The onload function must come before ...

How can you store JavaScript objects to files, including their methods, in a Node.js environment?

In reading about saving objects to files in Node.js here on Stack Overflow, I understand the process. However, I am curious if there is a method that allows for writing an object in a manner that would enable me to reload the object into memory along wit ...

The Bootstrap table fails to display any data retrieved from the server

I recently attempted to implement pagination using this resource: After setting up the HTML table on my page and confirming that the server-side code is functioning properly by checking the Network tab in the F12 tools, I ran into an issue. The data retur ...

In JavaScript, provide a boolean response to a callback function from a separate function

Working with the jQuery validate plugin involves utilizing a submitHandler callback function. This function determines whether the form submission should proceed based on its return value - false will prevent submission, while true will allow it to go thro ...

The metallic material in Substance Painter appears as a dark shade in A-Frame

After exporting an object as gltf from Substance Painter, I am importing it into my A-frame scene. Strangely, the metallic outer material appears dark in my current scene while other materials like plastic appear white and are visible. Despite already ha ...

Stylish mobile navigation styles with CSS

Hey there, I appreciate any help you can provide. I'm having trouble figuring out the right CSS code to modify the colors of my Mobile Menu only... I'd like to change the placeholder text as well as the text and background of the drop-down menu ...

Concealing divisions on a website with CSS styling

In my div, I have some text that I want to hide. <div style='visibility:hidden;' id='emailid'>$email</div> Although the visibility attribute successfully hides the text, it leaves behind empty space on the webpage where th ...

Concealing a Class on the Homepage in Joomla 3

Is there a way to only hide a certain class on the home page? <div class="search-wrapper"> .search-wrapper { background: none repeat scroll 0 0 #3d4895; height: 50px; margin-top: 10px; width: 100%; } I want this class to be visible ...

Is it possible to retrieve the complete file path in a form?

My goal is to retrieve a file using an input element of type "file". This element is located within a partial view, and I need to send it to the controller or request it there using "Request.Form["inputFile"];". However, this method only provides me with t ...

Having trouble retrieving react environment variables from process.env?

When developing my React App, I utilized a .env file to securely store some essential API keys. However, as I attempted to access these variables using process.env, I encountered an issue where the values appeared to be set as undefined. To launch the app ...

Exploring the power of Blowfish encryption with Java and JavaScript

I am facing an issue where I need to encrypt data using Blowfish on a java-based server and send it to a client. Despite successfully encrypting the data, I am unable to decrypt it on the client side. Below is my Java code snippet: byte[] kd = key.getByt ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Having trouble populating and submitting a selected option from a dropdown menu in Angular?

Upon loading the page, the Category dropdown automatically populates with data from the database. However, when I attempt to select a value from the dropdown and click a button to post the data to a specified URL, an error occurs: ERROR Error: Error tryin ...