Trigger Onclick Programmatically

ANB 181 Reputation points
2022-12-08T00:35:26.007+00:00

I have a div that provides some functionality when clicked.
However I want to call this click also when I initialize the page.

<div id="test1" @onclick="MyFunction()">
...
</div>

code {
...
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
test1.Click(); // I WANT TO TRIGGER THE CLICK IN HERE
//for this specific application I couldnt call MyFunction() directly in here... it needs to be called via the click event
}
}

Any help ?

Thx

Developer technologies .NET Blazor
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xinran Shen - MSFT 2,091 Reputation points
    2022-12-08T03:21:04.753+00:00

    Hi @ANB , from your description of this question, I think you want to use DOM.Click() instead of calling the onclick method directly in OnAfterRenderAsync() method. Please refer to this simple demo.

    Create a js file called MyScript.js in wwwroot:

    var BlazorTest = BlazorTest || {};  
    BlazorTest.setClick = function (element) {  
        element.click();  
    };  
    

    refer this js file in index.cshtml

    268453-image.png

    Then in your Razor Component

    268473-image.png

    Demo:

    268367-1208.gif

    -------------------------------------------------------------------------------------------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Brian Shen

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.