How to detect keypress event without using an input tag?

Platform: Event handling| Category: JavaScript Interop

To detect keypress event in a div tag, use the @onkeydown event on the current element. In the created example there is a div element with keydown event, and on rendering, the focus to the div element is set by using the JS Interop.

[script.js]
window.SetFocusToElement = (element) => {
         element.focus();
};
[index.razor]
@inject IJSRuntime jsRuntime
@using Microsoft.AspNetCore.Components.Web

<div class="jumbotron"  @onkeydown="@KeyDown"  tabindex="0"  @ref="myDiv">
            <h1 class="display-4"> @KeyPressed </h1>
</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);
        }
    }
    protected void KeyDown(KeyboardEventArgs args)
    {
        KeyPressed = $"Key Pressed: [{args.Key}]";// get key pressed in the arguments
    }
}

Share with

Related FAQs

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

Please submit your question and answer.