Search code examples
c#blazorblazor-webassembly

It possible to click outside an element to close it on Blazor?


It's a little duplicated Event for click outside a div or element to close it on Blazor, but no right answers.

(And I didn't find anything on my topic in Google)

In JS I just use "window.onclick" and "!event.target.matches('class')", and what can Blazor offer? Is it possible to implement it short and concisely, like in JS? Or is it useless?

Just in case - I want to do it in C#, but if the solution turns out to be "not so rosy", then I'll take JS.

Thanks to answers!


Solution

  • Thanks all for answers, but I have bad news — https://github.com/dotnet/aspnetcore/issues/28820

    They don't plan to do this in the near future, so there's no need to “crutch” in C#, I'll just use JS.

    In JS code it will look like this:

    window.onclick = function(event) {
        var dropdowns = document.getElementsByClassName("Class__name");
    
    if (!event.target.matches('.js-close')) {
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }