In my Blazor server-side project, I need to close a pop-up menu by clicking outside the menu.
I use a simple If statement to show/hide the pop-up by triggering the onClick event. but there is no such event to close the pop-up by clicking outside the pop-up menu. so the user should only close it by click on the element with the onClick event.
so my question is how we can resolve this issue better without using JS?
Thank you in advance.
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.
Solution: use Element. closest() inside a document click event listener. Element. closest() works its way to the top of the root of the DOM object to see if it can find a match for the query selector that was provided.
Here is what I do with a div to fire the onfocusout event where the ShowSelectBox variable is used by your if-statement to show or hide something:
<div tabindex="0" @onfocusout="@(() => ShowSelectBox = false)">
...
</div>
I used this in a blazor webassambly application, but should be the same for server-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With