Zeliax
Zeliax

Reputation: 5386

auto resizing textarea in a modal

I'm creating a ASP.NET Webpage using Bootstrap and jQuery.

I have recently implemented a modal to show a log. The modal is shown when clicking a link:

<a data-toggle="modal" data-target="#logData">Open</a>

<div class="modal fade" id="logData" tabindex="-1" role="dialog" aria-labelledby="logDataLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Log for @Html.DisplayFor(model => model.Alias)</h4>
            </div>
            <div class="modal-body">
                <textarea class="form-control log" rows="5" placeholder="Log is empty.">@Html.DisplayFor(model => model.Log)</textarea>    
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

The modal contains a textarea that doesn't autoresize.

I have found the following code:

$('textarea').each(function () {
    this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
    this.style.height = 'auto';
    this.style.height = (this.scrollHeight) + 'px';
});

which should enable my textareas to autoresize and it works other places in my code, but not in this modal above. At least not when typing in the textarea, but upon opening the modal it does seem to autoresize.

Does anyone have an idea of why? And eventually on how to fix it?

Thanks!

Upvotes: 0

Views: 2088

Answers (1)

Zied Feki
Zied Feki

Reputation: 872

You can use this code which will work if the textarea is not hidden (e.g in a modal that is not shown yet)

let setHeight = (input) => {

    input.style.overflow = 'hidden';
    input.style.height = 0;

    input.style.height = `${ input.scrollHeight + 2 }px`;

};

$('textarea').on('input, keyup', function () {
    setHeight(this);
})

for bootstrap modal, u can do something like this:

$('.modal').on('shown.bs.modal', function () {
    $(this).find('textarea').each(function () {
        setHeight(this);
    });
})

Upvotes: 1

Related Questions