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

314
Vistas
How to split a text and stay in max-width of a div

I have a textarea to make a text input. I now need to get that text split it into an array of words and add the words word for word into a div until my div is bigger than my given rows. Words that are to long need to be split by a hyphen and added into the next row. The problem is, the text breaks out of the max-width. How would I make the added words stay in the max-width and stop adding new words if the max rows are reached? I tried doing it like that:

        function textfield_handler()
        {
            let text = document.getElementById("tf-input").value.toString().split(/\s+/);

            let T1 = document.getElementById("tf-T1");
            let maxrows_top = document.getElementById("tf-toprows").value;
            T1.innerText = "";

            while (T1.getClientRects().length <= maxrows_top)
            {
                if(text.length === 0)
                    break;

                let word = text.shift();
                T1.innerHTML += '<a href="#">' + word + '</a>' + '\xa0';
            }
        }
.textline {
    margin: 0 auto;
    width: 100%;
    text-align: justify;
}

div.textline {
    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    -ms-hyphens: auto;
    hyphens: auto;
}

span.textline {
    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    -ms-hyphens: auto;
    hyphens: auto;
}
<div>
<label>Rows:</label>
<input type="number" min="1" id="tf-toprows" value="5">
<textarea id="tf-input">
  
</textarea>
<button type="button" id="generate-textfield" onclick="textfield_handler()">Convert text</button>
</div>

<div id="textfield-container" class="textline" style="width: 400px; background-color: lightgray;">
  <div class="textline" style="min-height: 50px; max-width: 800px" id="tf-T1">
</div>

Also the getClientRects().length was used to detect if the text is longer than my maxrows allow. But im searching for a better solution at the moment

about 4 years ago · Juan Pablo Isaza
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