qadenza
qadenza

Reputation: 9293

textarea height to fit the content before any typing

There is a lot "solutions" to expand textarea while typing inside.

I need to set its height before any typing so entire content should be visible by loading the page.

And why is this trivial task so complicated?

.txb{
display:block;
width:100%;
resize:none;
outline:none;
}
<textarea class='txb'>
lorem ipsum
dolor sit amet
consectetur adipiscing elit
sed do eiusmod tempor
incididunt ut labore
et dolore magna aliqua
</textarea>

Upvotes: 1

Views: 88

Answers (2)

VTr
VTr

Reputation: 718

Your requirement can't be done with CSS only, it very simple by using javascript. Just add an event to listen on page load complete, update the textarea height according it's content.

Hope my explanation in code snippet is clear enough.

window.addEventListener('load', event => {
    // Select all `textarea` elements and loop through every element
    document.querySelectorAll('textarea').forEach(textarea => {
        // Update current textarea height based on it's content
        textarea.style.height = textarea.scrollHeight + 'px';

        // Listen to `input` event and update the textarea height
        textarea.addEventListener('input', event => {
            // First, remove current inline height
            event.target.style.removeProperty('height');

            // Then, update it with new content
            event.target.style.setProperty('height', event.target.scrollHeight + 'px');
        });
    });
}, {once: true});
.txb {
    display: block;
    width: 100%;
    resize: none;
    outline: none;
}
<textarea class="txb">
lorem ipsum
dolor sit amet
consectetur adipiscing elit
sed do eiusmod tempor
incididunt ut labore
et dolore magna aliqua
</textarea>

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65796

Get the number of new line characters and set the height to be 1em for each one.

let ta = document.querySelector(".txb");

// Get the number of new line characters and set the height to 
// be 1em for each one.
ta.style.height = ta.value.split(/\n/).length + "em";
.txb{
display:block;
width:100%;
resize:none;
outline:none;
}
<textarea class='txb'>
lorem ipsum
dolor sit amet
consectetur adipiscing elit
sed do eiusmod tempor
incididunt ut labore
et dolore magna aliqua
</textarea>

Upvotes: 0

Related Questions