JavaScript failing to adjust span width as intended

In an attempt to adjust the width of a span dynamically based on its content, I am facing a challenge. My application consists of multiple spans in rows and users can modify the content of these spans. To ensure uniformity in span width after content changes, I aim to set each span's width equal to the maximum width among all spans.

For instance:

spanWidths = [ '50px', '34px', '56px', '87px' ]

The desired conversion of these spans would be:

[ '87px', '87px', '87px', '87px' ]

https://i.sstatic.net/hXLKj.png

When inspecting the box model for the span:

https://i.sstatic.net/twno1.png

Despite setting the width to 87px on the span, inspection shows a strange value like 57.98px due to border, padding, and content considerations.

The CSS style for the span is as follows (with consistent use of box-sizing: border-box):

.annotation-speaker {
    display: inline-block;
    font-size: 14px;
    line-height: 25px;
    background-color: rgb(224, 239, 241, 0.5);
    height: 25px;
    padding: 0px 5px 6px 5px;
    margin-top: 5px;
    border-radius: 4px;
    font-weight: 500;
    letter-spacing: 0.7px;
    overflow: hidden;
    text-align: center;
}

I am uncertain about how to calculate the spanWidths array with updated widths after modifying span content.

This is my current approach:

const css = getComputedStyle($speakerBox); // $speakerBox refers to the span
const r = $speakerBox.getBoundingClientRect();

const w = $speakerBox.scrollWidth + parseInt(css.paddingLeft) + parseInt(css.paddingRight);

maxSpeakerTagWidth = Math.max(maxSpeakerTagWidth, w);

Both r.width and $speakerBox.scrollWidth provide different values, leaving me confused about which one to prioritize.

To set all spans to the same width as maxSpeakerTagWidth:

$speakerBox.style.width = maxSpeakerTagWidth + 'px';

However, this solution doesn't seem to work as expected!

Answer №1

After tinkering around on JSFiddle (:P), I managed to come up with a solution that works perfectly there, but unfortunately, it's not behaving the same way in my project.

Check out my JSFiddle here

<html>
  <head>
    <style>
      .spanBox {
        font-size: 14px;
        line-height: 25px;
        background-color: rgb(224, 239, 241, 0.5);
        height: 25px;
        padding: 0px 5px;
        margin-top: 5px;
        border-radius: 4px;
        font-weight: 500;
        letter-spacing: 0.7px;
        text-align: center;
        display: inline-block;
        margin-left: 1em;
        box-sizing: content-box;
      }

      .input {
        display: block;
        margin-left: 1em;
      }
    </style>
  </head>
  <body>
    <!-- Just type in the input box press enter -->

    <span id="span1" class="spanBox">gg</span>
    <span id="span2" class="spanBox">gg</span>
    <span id="span3" class="spanBox">gg</span>
    <span id="span4" class="spanBox">gg</span>
    <span id="span5" class="spanBox">gg</span>

    <input onkeypress="change(event)" class="input" />
  </body>
  <script>
     let maxW = -1;
     const change = (e) => {
       if(e.keyCode === 13) {
          const val = e.target.value;

          const $span1 = document.getElementById('span1');

          $span1.textContent = `${val}`;

          calcMax();
       }
     }

     const calcMax = () => {
        maxW = -1;
        for(let i = 1; i <= 5; i++) {
            const $span = document.getElementById(`span${i}`);

            if($span.style.width === '') {
              const r = $span.getBoundingClientRect();

              maxW = Math.max(maxW, r.width);
            }
            else {
              $span.style.width = '1px';

              maxW = Math.max(maxW, $span.scrollWidth);
            }
        }
        setTimeout(() => update(), 100);
     }

     const update = () => {
       console.log("MAX ", maxW);

       for(let i = 1; i <= 5; i++) {
           const $span = document.getElementById(`span${i}`);

           $span.style.width = maxW + 'px';
       }
     }

     calcMax();

  </script>
<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

Issues encountered while trying to implement HTML text within span tags

In my code snippet, I am using a span element: <span> {textToRender} </span> The purpose of this code is to render HTML text (as a string) within a span element. some text <br/> some text <br/> some text <ol>text However, wh ...

"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

"Node.js: The Importance of Rest for Optimal Performance

Imagine this situation: As part of my cron jobs, I am utilizing an external service that limits requests to every 3600 seconds. This service's API is similar to GetPersonForName=string. I have multiple people in my database and it's necessary to ...

Issue with button click functionality within Angular grid's Celltemplate

Has anyone experienced issues with the click event not working when using celltemplate in AngularJS? $scope.format = function(val){ return val.replace(/\//g, ""); }; var executionColumns = { data: [], ...

Encountering a 401 error while attempting to exchange Faceit OAuth authorization code for access token

I am having issues with exchanging a code for a token on the Faceit OAuth. The documentation states the following: Exchanging the Authorization Code for an Access Token The third-party app needs to make a server-to-server call, providing the Authorization ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...

Ways to compel Capacitor Application to reload through code

Is there a way to programmatically restart my app so that it functions seamlessly across all platforms - electron, iOS, Android, and web? If so, how can I make this happen? ...

Turn off the debugger statement using your web browser

I have a piece of code with the debugger keyword and I want to style it. However, every time I refresh the page, the browser's debugging window (IE, FF, Opera) stops at the debugger line. Is there a way to toggle or disable the debugger keyword throu ...

Adjust `theme-color` as the class and theme of the page are switched

My website has a JavaScript toggle that changes the color/theme of the page by adding/removing classes on the html element. The default theme is white, the second theme is black (.dark-mode), and the third theme is beige (.retro). The JavaScript code for ...

I am experiencing issues with launching chromium while running Puppeteer on Windows 11 using node js v19.4

Upon following the installation instructions in the documentation to install puppeteer with npm install puppeteer, I attempted to run the example for downloading a webpage as a PDF. However, every time I try to execute the code, Node.js returns the followi ...

In ReactJS, changing one setState property triggers a cascade of changes in other properties

Within my React application, I am facing an issue where changing a state property in the parent component results in an unexpected change in another state property. The setup involves a table in the parent component and form fields in the child component. ...

What is the best way to handle errors generated by my jsdom.jqueryify callback function?

When running this code in node.js, the output is a stack trace of an error that occurs on line 9. Surprisingly, the error on line 7 seems to be 'absorbed' by Node. Even when wrapped in a try/catch statement, the detailed stack trace output is not ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

Implement dynamic CSS color selection based on server-side data

Introduction At our company, we manage a large client website in Optimizely (ASP.NET MVC) that hosts multiple smaller sites for different regions and important customers. Currently, our frontend team creates various themes using SASS to CSS conversion, w ...

Avoid overflow of a flex element within the <body> tag by ensuring its child with overflowing content takes up 100% of its width

I am facing an issue with my dashboard setup that includes a sidebar. I want the content area to have horizontal overflow scroll, but instead of that, it overflows its parent element. I experimented with flex and grid-template-columns values (1fr 5fr) with ...

The scroll function remains unchanged when using overflow-y scroll and border radius

I need help with styling a div that will contain a large amount of text on my webpage. I want to use the overflow-y property for scroll, but the issue arises when trying to style the scroll bar with a radius. Check out this jsfiddle link for reference: ht ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Modify the specified pattern with regex only if it does not appear in a particular location in the content

Our tool development heavily relies on regex for various functionalities. One key aspect involves replacing placeholders with actual values dynamically using standard JavaScript's `RegExp`. All placeholder formats are similar to this: {{key}} In mo ...

Discover an Easy Way to Scroll to the Bottom of Modal Content with Bootstrap 5 on Your Razor Page

Currently, I am developing a web application that utilizes Razor Pages and Bootstrap 5 modals to showcase dynamic content. The challenge I am facing is ensuring that the content inside the modal automatically scrolls to the bottom when the modal opens or w ...