Blazor auto scroll Textarea to bottom

Viewed 1999

How can I auto-scroll a TextArea in Blazor, to the bottom, every time its value changes?

To test it, I tried it with an inline JS to change the size of the Element I found here on Stack Overflow: " oninput="this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';" "

It works, as long I fill the TextArea manually. But it does not work when filling it from Backend like i want to:

        protected async System.Threading.Tasks.Task TestButtonClick0()
        {
            TextAreaText += ">> SPAM Test \n";
        }
1 Answers

There are a couple of ways you could auto-scroll a textarea. However, it probably can't be done with inline JavaScript as events like "onchange" and "oninput" are triggered by user actions. So you'll need to call a JavaScript function to do it when programmatically updating the textarea value. The simplest way would be to add a JavaScript function like:

function scrollToEnd(textarea) {
    textarea.scrollTop = textarea.scrollHeight;
}

And then invoke it from the Blazor page:

@page "/"
@using Microsoft.JSInterop
@inject IJSRuntime JS

@functions{
    ElementReference TextAreaRef;

    string TextAreaText = "Example auto-scroll\n";

    void ScrollToEnd() {
        JS.InvokeVoidAsync("scrollToEnd", new object[] {TextAreaRef});
    }   
}

<button class="btn btn-primary m-2" @onclick="ScrollToEnd">Add Line</button>
<br/>
<textarea @ref=TextAreaRef value="@TextAreaText" class="form-control" rows="5"></textarea>

See this Blazor Fiddle for a working example:

https://blazorfiddle.com/s/3ioprd8b

Related