Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
Change width of contenteditable div by chuncks based on text

I'm trying to change the width of a div based on the content of the div:
Lets say initially the div has a width of 100px, I want it to remain at that width until the user has filled up 90px with text.
When this arrive the width of the div should be incremented by a fixed value. if the user writes even more (190px) the div will again have its width incremented. I tried using the clientWidth of the div like this:

get style(): string {
    if (!this.el) {
      return `
      width: 100px;
      line-height: ${DEFAULT_HEIGHT}px;
      max-height: inherit;
    `;
    }
    let divWidth = 100;
    const maxWidth = window.innerWidth - SCROLLBAR_WIDTH;
    while (this.el.clientWidth > divWidth * 0.9 && divWidth < maxWidth) {
      const width = width + 100
      if (width > maxWidth) {
        break;
      }
      divWidth = width;
    }
    return `
    width: ${divWidth}px;
    line-height: ${DEFAULT_HEIGHT}px;
    max-height: inherit;
  `;
  } 

but it does compare the width of the div with itself and not the content of the div.

Thanks in advance,

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can relate to this answer to get the content width: https://stackoverflow.com/a/47224153/12933115

My recommendation is that you use two nested DIVs like this:

<div id="container">
    <div id="content"></div>
</div>
<input id="txtBox" />

The div#container would have a fixed size, whereas the div#content wouldn't.

#container {
    width: 100px;
}
#content {
    max-width: fit-content;
    max-width: -moz-fit-content; /* For Mozilla Firefox */
}

Now, you detect the typing instead of the width. Then, you check the width of the inner DIV within the event listener.

const input = document.getElementById("txtBox");
input.addEventListener("input", () => {
   // Check the width of the inner DIV (#content) here...
   // If the width of the inner width exceeds your limit, then you change the width
   // of the container DIV (#container).
});

The above was a general explanation. You'll figure out how to apply this according to your needs.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!