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

315
Visualizações
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 à 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