Mdarende
Mdarende

Reputation: 739

In my Blazor Server side app: How can I fire an action when anywhere on the razor page's body is clicked (except a button)?

In my blazor server side app I want to listen to the mouseclick event on a razor page, and when mouseclick occurs (except on a button), I want to run a method. I have tried following with JavaScript but didn't worked for me:

in my _host.cshtml added following script:

window.addDocumentClickListener = () => {
  document.addEventListener('click', function (e) {
    if (e.target.tagName.toLowerCase() !== 'button') {
      DotNet.invokeMethodAsync('MyProjectName', 'HandleMouseClick');
    }
  });
};

in my Razor page:

@inject IJSRuntime JS
    ...
    ...
@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender )
        {
            await JS.InvokeVoidAsync("addDocumentClickListener");
        }

    }
    [JSInvokable]
    public void HandleMouseClick()
    {
        Action_On_Mouseclick();        
    }
}

Upvotes: 0

Views: 29

Answers (1)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30375

Here's a demo with no extra JS, using the Counter page. It has a full page div with click event handler. Note that you need to using stopPropagation="true" to prevent bubbling up on buttons and other UI elements with UI events.

@page "/counter"

<PageTitle>Counter</PageTitle>
<div class="underlay" @onclick="BackClick">
    <div>
        <h1>Counter</h1>

        <p role="status">Current count: @currentCount</p>

        <button class="btn btn-primary" @onclick:stopPropagation="true" @onclick="IncrementCount">Click me</button>
    </div>
</div>

<style>
    .underlay {
        position: fixed;
        width: 100%;
        height: 100%;
        background-color: transparent;
    }
</style>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        Console.WriteLine("Button Clicked");
        currentCount++;
    }

    private void BackClick()
    {
        Console.WriteLine("Background Clicked");
    }
}

Upvotes: 1

Related Questions