-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
When using the new @onevent:preventDefault
directive to prevent the default event behavior for events, I noticed that in order for this to work, there needs to be a @onevent
handler registered anywhere on the page.
Apparently, server-side Blazor registers every event just once on the document instead of on individual elements. So e.g. @onclick="…"
causes the click
event to be subscribed on the document. Just using @onclick:preventDefault
on the page does not appear to register this global event handler on document, so the preventDefault()
call is also never made in the handler.
My use case for this is managing focus with buttons: When you click a button, then the button stays focused after clicking it, causing the focused style to be applied. In order to avoid this, you can subscribe to the mousedown
event in JavaScript and just prevent the default behavior:
<button id="test">Test</button>
<script>
var button = document.getElementById('test')
button.addEventListener('click', () => console.log('Clicked'));
button.addEventListener('mousedown', (evt) => evt.preventDefault());
</script>
Doing the same in Blazor would look like this:
<button @onclick="Click" @onmousedown:preventDefault>Test</button>
@code {
void Click() => Console.WriteLine("Click");
}
This however does not work if there isn’t also some mousedown
handler registered somewhere. As soon as you add one literally anywhere, it works:
<button @onclick="Click" @onmousedown:preventDefault>Test</button>
<div @onmousedown="() => { }"></div>
@code {
void Click() => Console.WriteLine("Click");
}
This is using server-side Blazor on ASP.NET Core 3.1.