Blazor

How do you get the target element onclick event in Blazor?

 How do you get the target element onclick event in Blazor?

Blazor does not have support to manipulate DOM elements directly, but we can still achieve it by using JavaScript interop. By creating a reference to an element, we can send it as a parameter to the JavaScript method via interop. In that JavaScript method, we can manipulate the DOM elements.

[script.js]
window.setElementText = (element, text) => {
    console.log(element);
    element.innerText = text;
}

Refer the script file in HTML page

[index.html/_Host.cshtml]
<head>
 .....
 <script src="~/script.js"></script>
 ....
</head>
[Counter.razor]

@page "/counter"

@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<p>Last button clicked: @lastButtonClicked</p>

<button @ref=button1 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button1))">Click me</button>
<button @ref=button2 class="btn btn-primary" @onclick="@(()=>IncrementCount1(@button2))">Click me</button>


@code {

    private ElementReference button1;
    private ElementReference button2;

    private int currentCount = 0;
    private string lastButtonClicked = "None";

    private async void IncrementCount(ElementReference element)
    {
        currentCount++;
        lastButtonClicked = "Button 1";
        await JSRuntime.InvokeVoidAsync("setElementText", element, "Button 1 was clicked");

    }
    private async void IncrementCount1(ElementReference element)
    {
        currentCount++;

            lastButtonClicked = "Button 2";
            await JSRuntime.InvokeVoidAsync("setElementText", element, "Button 2 was clicked");
    }
}

 

Nitin Pandit

With over 10 years of vast development experience with different technologies, Nitin Pandit is Microsoft certified Most Valued Professional (Microsoft MVP) with a rich skillset that includes developing and managing IT/Web-based applications in different technologies, such as – C#.NET, ADO.NET, LINQ to SQL, WCF, and ASP.NET 2.0/3.x/4.0, WCF, WPF, MVC 5.0 (Razor), and Silverlight, along with client-side programming techniques, like jQuery and AngularJS. Nitin possesses a Master’s degree in Computer Science and has been actively contributing to the development community for its betterment. He has written more than 100 blogs/articles and 3 eBooks on different technologies to help improve the knowledge of young technology professionals. He has trained more than one lakh students and professionals, as a speaker in workshops and AppFests, conducted in more than 25 universities in North India.