HandleClick seems to only handle left clicks, but it looks like I can use onmouseup
and the MouseEventArgs.Button
property to detect the right click.
The problem is that the typical browser-provided context menu comes up. Is there a way to prevent that? I don't see anything like preventDefault() in Blazor.
Update: apparently we can do @onmouseup:preventDefault
but the context menu still shows
OK, I figured it out:
<div oncontextmenu="return false;" @onclick="HandleClick" @onmouseup="HandleMouseUp" >
this is a div
</div>
@code {
void HandleClick(MouseEventArgs args)
{
Console.WriteLine("This is a left click");
}
void HandleMouseUp(MouseEventArgs args)
{
if (args.Button == 2)
Console.WriteLine("This is a right click");
}
}
The key is the oncontextmenu="return false;"
javascript in the div itself.
You can use the @oncontextmenu directly in blazor. combined with @oncontextmenu:preventDefault="true" it does not show the context menu.
<div @onclick="HandleClick" @oncontextmenu="HandleRightClick" @oncontextmenu:preventDefault="true" >
this is a div
</div>
@code {
void HandleClick(MouseEventArgs args)
{
Console.WriteLine("This is a left click");
}
void HandleRightClick(MouseEventArgs args)
{
if (args.Button == 2)
Console.WriteLine("This is a right click");
}
}
Thanks for the info it helped me a lot
Just a tip for anyone using this I made my own context menu component using a div with labels for menu items and was finding the default context menu would still show up occasionally on things like a double click with the right mouse button or if I held down the right mouse button for too long. turns out the right click was happening on my menu component and then showed the default menu, as it was shown over the current mouse position. so adding the oncontextmenu="return false;" to my menu component was also required to stop it completely.
just sharing as it took me too long to figure out why it was still coming up
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