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

Creating a secondary title for a Bootstrap Navigation Bar

I have a unique Bootstrap 4 website that features a navbar. The navbar consists of a special brand section with an image and title text, followed by the rest of the navbar elements. You can view it here: https://jsfiddle.net/zmbq/aq9Laaew/218793/ Now, I a ...

Guide to implementing a universal animated background with Angular components

I'm having trouble figuring out why, but every time I attempt to use a specific code (for example: https://codepen.io/plavookac/pen/QMwObb), when applying it to my index.html file (the main one), it ends up displaying on top of my content and makes ev ...

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

In jqGrid's gridComplete event, we can use the getRowData method to retrieve the value of a

Seeking guidance on extracting variables from jqGrid getRowData method While iterating through rows, I simply want to retrieve the ID and Phrase column values into separate variables gridComplete: function () { var allRowsInGrid = $('#list'). ...

The Angular 2 view will remain unchanged until the user interacts with a different input box

I am currently working on implementing form validation using Reactive Forms in Angular 2. Here is the scenario: There are two input fields Here are image examples for step 1 and step 2: https://i.stack.imgur.com/nZlkk.png https://i.stack.imgur.com/jNIFj ...

Enhancing webpage styles with AngularJS

Just starting out with AngularJS and eager to get the best approach to tackle this challenge. Describing my dilemma: I have an anchor element that, when clicked, needs to toggle between classes "show-all" and "hide-all" while also updating the styling of ...

Tips for repairing a horizontal line at the bottom of the <TD> tag and placing text on top

I am working with an HTML table that contains a single TR tag and two TD tags. Each TD has two HR tags creating horizontal lines, along with some text. I am looking for a way to keep the text aligned at the top of the TD and the horizontal line at the bott ...

Guide to modifying the text color of a Primefaces/jqPlot line chart:

I've implemented a basic JSF line chart with PrimeFaces (using jqPlot library) in my project: <p:lineChart id="linear" value="#{team.chart}" title="Lap Times" xaxisLabel="Lap" yaxisLabel="Time ...

Large data sets may cause the Highchart Bar to not display properly

Currently, I am working on a web project that displays traffic usage in chart mode using Highchart Bar. The issue I am facing is that there are no errors thrown when running this code. <script type="text/javascript"> $(function () { $(&apos ...

When invoking a JavaScript method, the context variable 'this' is lost

I have developed a basic pointer to a method like this: export class SmbwaService { getExistingArsByLab(labId: number): Observable<SmwbaAr[]> { this.otherMethod(); } otherMethod(): void { } } let method: (x: number) => ...

Images flicker as they transition

Within my HTML body, I have the following: <a id="Hal9000"> In addition, there is a function included: function Hal(MSG){ document.getElementById("Hal9000").innerHTML = "<img src=\"+preloadImage("HAL9000.php?Text="+MSG)+"\"\>" ...

Form submissions are not saving checkbox answers

As a beginner, I'm struggling to save the checkbox answers on the page after submission. The code below is quite lengthy (checkboxes start at 314). I have a feeling that I might be missing a piece of code, but I just can't seem to pinpoint what i ...

The next.js Head component that is imported from next/head is not functioning correctly when used on share pages

I recently switched my website from create-react-app to create-next-app, but I'm having issues with the Head(app/head) component. Let's say I have a blog section with pages structured as follows: pages/blog/index.js and pages/blog/[slug].js. In ...

Utilizing React with file system and path dependent packages

Is there a way to utilize the quick.db package in my ReactAPP with hooks, even though React does not allow the use of FS & Path which are required for this package? I am encountering the following errors: ERROR in ./node_modules/file-uri-to-path/index.js ...

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

What steps can you take to prevent a potential crash from occurring when an unauthorized user attempts to access a page without logging in?

I've encountered an issue where the app crashes when trying to access a page that requires logging in. The reason for this crash is because the page attempts to load undefined data, resulting in the error: TypeError: Cannot read property 'firstN ...

The error message states that there is a problem with the function task.dueDate.toDate,

I am currently utilizing Firebase as my database along with Next.js. I have encountered an issue when trying to read data from Firebase, specifically related to the due date field, which is of timestamp datatype. Here is the code snippet where I attempt to ...

A Sweet Alert to Deliver your Morning Toasty Message

I seem to be encountering an issue with my toast message. Instead of the toast popping up immediately after submitting the form, it keeps appearing even if I haven't submitted the form and even when navigating from another page to this one, the toast ...

Can you explain Node.js and its applications as well as how it is commonly used?

A while back, during my time at IBM when I was immersed in learning, I came across something known as BlueMix, a cloud product. Within BlueMix, there was a rather primitive component called Node.js. Since that moment, I've been filled with curiosity a ...

Encountering an error with TypeScript in combination with Angular 2 and Grunt. The error message is TS

Currently in my angular2 Project, I am utilizing grunt for automating the compilation of my typescript files. Everything seems to be working fine as my files are compiling, but I keep encountering errors: app/webapp/ng2/audit_logs/auditLogs.ts(2,3): erro ...