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.


window.SetFocusToElement = (element) => {


@inject IJSRuntime jsRuntime

<div tabindex="0" @ref="myDiv"> 
    To focus this div element when refreshing the page. 

@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);

View Sample in GitHub

Share with

Related FAQs

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

Please submit your question and answer.