Live Chat Icon For mobile
Live Chat Icon

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

Platform: Blazor| Category : Event handling, Tips and Tricks

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");
    }
}

Share with

Related FAQs

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

Please submit your question and answer.