How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content.

I have tried the following code:

$('textarea').on('blur', function() {
    var textAreaWidth = $(this).val().length;
    $(this).attr('cols', 'textAreaWidth');
});

However, this solution is not ideal. I am looking for a better way to achieve this. Any ideas?

Answer №1

If you only want to reduce the size, make sure to check if the value is less than 20 and then decrease the number of columns. Give this a try:

<textarea rows="2" cols="20"></textarea>

$('textarea').on('blur', function() {
    var textAreaWidth = $(this).val().length;

    if (textAreaWidth < 20) {
       $(this).attr('cols', textAreaWidth);
    }
    $('textarea').on('keypress', function() {
       $(this).attr('cols', '20');
    });   
});

http://jsfiddle.net/4bccm/

Answer №2

Make sure to eliminate the single quotes surrounding 'textAreaWidth' within

$(this).attr('cols', 'textAreaWidth');

'textAreaWidth' is a variable and should not be enclosed in quotes.

Answer №3

$('input').on('focus change', function() {
    $(this).attr('size', $(this).val().length);
});​

Watch as it dynamically adjusts its size based on your input.

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

Clicking on text within a DIV using jQuery

How can I use jQuery to show an "alert" when text inside a DIV is clicked, excluding images and other tags? The texts are contained within various DIVs along with images and tags. Is there a way to achieve this using jQuery? Check out the jsFiddle example ...

"Failed to insert or update a child record in the database due to a SQL

I encountered an issue while trying to perform the following transaction: static async save(habit){ await db.beginTransaction; try { await db.execute('SELECT @habitId:=MAX(habits.habitId)+1 FROM habits'); await db.execute( ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

Exploring the idea of how a Node.js server works

Although I have a good understanding of jQuery, I am new to modern JavaScript frameworks that have been introduced in the past few years. In the example provided, I can see how index.html functions and how server.js handles requests from it. However, I am ...

Guide to creating a nested list using the jQuery :header selector

Here is the structure of my html: <h1 id="header1">H1</h1> <p>Lorem ipsum</p> <h2 id="header2">H2</h2> <p>lorem ipsum</p> <h2 id="header3">H2</h2> <p>lorem upsum</p ...

The offcanvas menu in the NextJS Tailwind website does not handle hover or tap events properly when outside of the parent dimensions

My header includes an off-canvas menu that slides in from the right side. Everything seems to be working fine, except for one issue: when the menu is open and visible, the mouse and touch events pass through it to the content underneath. Check out the cod ...

Utilizing AJAX to dynamically update a DIV element in CodeIgniter's controller

I need to continuously update a small chat between two users every minute. The functionality is working, but I am struggling with implementing an AJAX call to update the DIV that displays the messages. var interval window.onload = function(){ interval ...

What sets apart the CSS file directories in a React application compared to those in an Express server?

For instance, there is a public folder that contains all the css files, and a separate view folder for ejs files. When linking the css file in the ejs file, the code usually looks like this: <link rel=”stylesheet” href=”styles.css”> or like ...

Arranging particular placement

How can I position my links to the right of the second photo (opus1) and slightly below the first photo (coverPhoto)? I've tried various methods but haven't found a simple solution yet. <!DOCTYPE html> <html lang="en"> <head ...

Experimenting with JavaScript within an Immediately Invoked Function Expression

My team leader is requesting that I encapsulate my JavaScript code within an Immediately-Invoked Function Expression (IIFE). However, I am struggling to use spyOn in my Jasmine spec file. How can I properly use spyOn on the following: (function(){ fu ...

Adjusting the color of the legend on a LineChart in ExtJS 4 on-the-fly

I've been trying to find information on how to modify the color of the x legend in a Line chart without success. Can anyone help me with this? I have included an image of the chart for reference. ...

Improper ordering using insert method within a forEach loop

I have an array containing objects that I need to import into a sqlite3 database using a forEach loop. The process is working correctly, but I noticed that the objects are not being imported in the same order as they appear in the database. This is my app ...

Is it possible to manipulate CSS on a webpage using javascript?

I have incorporated this piece of JavaScript to integrate a chat box onto my website: window.HFCHAT_CONFIG = { EMBED_TOKEN: "XXXXX", ACCESS_TOKEN: "XXXXX", HOST_URL: "https://happyfoxchat.com", ASSETS_URL: "https://XXXXX.cloudfront.ne ...

Determining the scroll position of a JQuery Mobile collapsible set upon expansion

I am utilizing jQueryMobile (v1.4.0) collapsible set / accordions to showcase a list of elements along with their content, which can be seen in this jsFiddle. <div id="List" data-role="collapsible-set"> <div data-role="collapsible" data-conte ...

Troubleshoot: CSS class H2 style is not displaying correctly

I have the following code in my .css file: h2.spielbox { margin-bottom:80px; color:#f00; } a.spielbox { text-decoration:none; background-color:#aff; } However, in my html file, the h2 style is not ...

Is there a way to convey a transition MUI property from a parent component to its child component in React?

My current setup involves a parent component with a button that triggers the opening of a snackBar from MUI (child component) upon click. To enhance the user experience, my teacher suggested adding a transition effect to the onClick event so that the snack ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

Tips for altering the color of an image using CSS attributes

I am looking to create a male Head component in this design draft and modify the CSS according to the skin prop. I have attempted to use filter and mix-blend-mode properties, but have not found a solution yet. Any guidance on how to achieve this would be ...

Can you have two navigation bars and a picture all in one Bootstrap layout?

I have a requirement to use a single image on two different Bootstrap navbars. However, the issue is that the image appears split between the two navbars.https://i.stack.imgur.com/jUnIL.png My goal is to display the full image without it being divided bet ...

Awaiting the completion of multiple asynchronous function executions

I am currently working on a promise function that executes an async function multiple times in a loop for different data. I would like to ensure that all async functions are completed before resolving the promise or calling a callback function within a non ...