Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda