Adjust the width of the inline textarea using HTML and CSS to match that of the input field

Is it possible to create an inline textarea element using CSS that is selectable but still seamlessly integrated into a sentence without specifying the number of columns? Here's an example with a static number of characters (cols="11"):

<p>To run nload for your device run <textarea readonly cols="11">nload p3p1</textarea> in your terminal.</p>

The accompanying CSS looks like this:

textarea {
    display: inline;
    border:none;
    resize: none;
}

Is there a way to achieve this dynamically, so each textarea appears inline and seamlessly within a paragraph without needing to specify the number of columns in the CSS? If CSS doesn't provide a solution, can it be done through pure JavaScript?

Answer №1

To determine the width of the input text, you should render the text and calculate its width based on that rendering.

One method is to copy the text into a hidden span element and evaluate its width with the following code snippet:

jQuery('input').on('input', function()
{
    var $this = jQuery(this);

    // Create a widthSpan if it doesn't already exist.
    document.$widthSpan = document.$widthSpan || jQuery('<span style="display: none" />').appendTo(document.body);

    document.$widthSpan.text($this.val());
    $this.css('width', document.$widthSpan.width() + 5);
}).trigger('input');

You can test the functionality with this interactive example: http://jsfiddle.net/687uew37/.

Keep in mind that this is just a demonstration that updates as soon as the input content changes. You may need to make adjustments based on your specific implementation and requirements.

Answer №2

Incorporate JavaScript to dynamically adjust the width of your textarea based on the number of characters present within it.

HTML:

<p>For device load monitoring, input <textarea class="tx" readonly>nload p3p1</textarea> into your terminal.</p>

<p>Similarly, you can utilize this pattern by entering a query in <textarea class="tx" readonly>your textarea where you type numerous lines of text. </textarea>Even after adding additional content, it will seamlessly blend with your existing text.</p>

CSS:

p{
line-height:1.5em;
font-size:14px;
}

textarea {
    margin-bottom:-0.3em;
    border:none;
    overflow:hidden;
    height:14px;
    display:inline;
    white-space: nowrap;
}

Jquery:

$(document).ready(function(){
    $('textarea').each(function(){
        //Width of a character:
        var chars = 8;
        //Calculate total characters in textarea:
        var txLength = $(this).val().length;
        //Compute required width:
        var txWidth = chars * txLength;
        //Adjust the width:
        $(this).css({'width':txWidth,'resize':'none'});
    });
});

The process involves handling each textarea individually. By having a predefined font-family and knowing the average character width, you are able to estimate the appropriate width for your textarea using jQuery's .css() function.

Here, the variable chars stores the average character width value. By multiplying the number of characters by this average width, you can determine the suitable width for the textarea and apply it via CSS using jQuery.

Check out the working example here: http://jsfiddle.net/ys2Lfrt8/5/

Limitations: Not responsive, but responsiveness can be achieved using @media-queries

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 jQuery to trigger a Bootstrap modal when a button is clicked

I've been attempting a simple task, but it appears to be unsuccessful. I'm trying to handle the click event of a button inside a bootstrap modal, and so far, nothing happens when clicking the button. My guess is that my jQuery selector for select ...

Ways to transfer several files while transferring just one file

When you save a complete webpage, a .htm file is created along with a folder containing all the icons and scripts for the page. If you relocate the .htm file, the accompanying folder also moves to the same location. Similarly, if you move the folder, the ...

Why am I receiving an error message stating "undefined is not a function" when trying

I am attempting to create a popover using the Angular UI pop over feature. I have loaded my HTML and compiled it, but when I run my program and click on the star icon (where I display the popover), I receive an error stating that 'undefined is not a f ...

Encountering an issue with the for loop in React Native when using FlatList

As a beginner in programming, I am eager to dynamically render a list. The Navbar parent component holds the state with different Food Types categories such as Mexican and Chinese, each with its corresponding menu. My goal is to display each Food Type fol ...

Struggling to update the state of an array using ReactJS and unsure of how to iterate through it

Currently, I am in the process of developing a movie voting application for me and my friends using React. I have made significant progress but I am facing issues with setting or updating the state of the 'rating' object. The structure of the ar ...

Hide the navigation menu when a page link is selected

Within my Angular 8 application, a fixed navigation bar is positioned at the top of the screen. Upon hovering over a dropdown nav link, a menu will appear for the user to explore. However, when a user clicks on one of these menu links, Angular Routing is ...

React: Why aren't class methods always running as expected?

I created a class component that retrieves a list of applications from an external API. It then sends a separate request for each application to check its status. The fetching of the applications works well, but there is an issue with the pinging process ...

Issue with React component timer becoming unsynchronized with numeric input field

My number field and countdown timer are not staying synchronized. Even though I can start and pause the countdown, whenever I try to change the number value after pausing, the numbers get out of sync. The gap between the two values keeps growing as time p ...

Issue encountered when trying to integrate a CSS sticky footer with a liquid/fluid layout

I've been attempting to incorporate the CSS Sticky Footer technique demonstrated at cssstickyfooter.com. (I also experimented with Ryan Fait's solution without success). I believe I've followed all the instructions correctly. I have a conta ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Updating the background of the <html> tag using jQuery

Is there a way to modify this CSS using jQuery? html { background: yellow; } Attempting the following code does not yield the desired results: $('html').css('background','red'); ...

Attempting to decode JSON data

I'm new to node.js and trying to learn how to send a JSON object using REST. However, I keep getting an error message that says "SyntaxError: Unexpected token  in JSON at position 0". I've checked the JSON using an online validator and it seem ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

What is the solution for positioning an input or select element at the end of a tr element?

Within a table, I have a form where each <td> tag contains either a <select> or an <input>. However, due to the varying lengths of the labels within the <td> tags, the <input> or <select> fields are not aligned in the sa ...

Troubleshooting lack of output in Console.log (NodeJs)

I am facing an issue where I can't see any output when trying to console log a JavaScript code using Node.js. const pokemon = require('pokemon'); pokemon.all(); var name = pokemon.random(); console.log(name); I am unable to even display a ...

What is the best way to retrieve error messages from a transaction with ethers.js?

Incorporating a custom error in my Solidity contract: error Documents__AlreadyExist(string hash); The modifier I utilize is as follows: modifier alreadyExist(string memory hash) { if (s_documentsHashes[hash]) { revert Documents__AlreadyExi ...

Jquery Banner Fade In animation malfunctioning

I am facing an issue with my banner on various browsers, especially IE 7,8, and possibly 9. When the fade-in effect is applied at the bottom of the banner, the shadows underneath turn black. Is there anyone who can help me resolve this issue? Website: ww ...

Flexbox is not properly repeating elements horizontally

I am struggling to align text boxes horizontally within ngFor loop, and I can't seem to pinpoint the mistake. Here is the HTML code from the parent component: <div class="maintenance-section"> <div class="yearly"> ...

Ways to combine X and Y velocities into a single velocity

Is there a way to combine the X and Y Velocity into a single Velocity without considering the angle? var velocityX = some value; var velocityY = some value; // Need to convert both X and Y velocities into one combined velocity ...

I'm baffled by the unexpected result I'm getting when using 'foreach' in node.js

Recently delving into node.js, I've encountered a puzzling issue. I'm perplexed as to why my output appears as: ciao data data instead of: data data ciao Below is the code causing this unexpected output: fs.readdir("sender", (err, fil ...