This code will help you to understand how to detect keypress event without using an input tag.
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 } }
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
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.
need an explanation for this answer? contact us directly to get an explanation for this answer