
Javascript interoperability
I love this term that sounds smart when you say it ^^. In short, you just need to add a small piece of Javascript code to your project and simply give focus to an element identified by a … id, of course.
[cc lang=”csharp” ] window.jsfunction = { focusElement: function (id) { const element = document.getElementById(id); element.focus(); } } [/cc]
Save this code in a .JS file with the name of your choice. Then declare between the Header tags of your index page. For Blazor Webassembly applications it’s in the wwwwroot/index.html folder. For Blazor Server applications it’s in the _Host.cshtml file.
I don’t think I can teach you anything by telling you it’s like this:
[cc lang=”csharp” escaped=”true” width=”600″ nowrap=”0″ line_numbers=”0″ theme=”vsdark”] [/cc]
What about the Blazor code?
Just add the interface IJSRuntime to your page .razor. As our code javascrpit returns nothing, it will then be enough to call it via InvokeVoidAsync :
[cc lang=”csharp” escaped=”true” width=”690″ line_numbers=”0″ theme=”vsdark”] @inject IJSRuntime js @code { private string _pass; private async void clickOK() { if (String.IsNullOrEmpty(_pass)) await Focus(“idPassWord”); else { // your code } } public async Task Focus(string elementId) { await js.InvokeVoidAsync(“jsfunction.focusElement”, elementId); } } [/cc]Once again, you will have understood it, it’s super simple!
