Live Chat Icon For mobile
Live Chat Icon

How to set the focus to an element in Blazor?

Platform: Blazor| Category : General, JavaScript Interop

To set the focus to a HTML element in Blazor, use the JavaScript interop to pass the HTML element and then use focus JavaScript method.

[script.js]

window.SetFocusToElement = (element) => {
         element.focus();
};
[index.razor]

@inject IJSRuntime jsRuntime

<div class="jumbotron" tabindex="0"  @ref="myDiv">
</div>

@code {
    string KeyPressed = "";
    protected ElementReference myDiv;  // set the @ref for attribute

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await jsRuntime.InvokeVoidAsync("SetFocusToElement", myDiv);
        }
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.