Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda