Skip to content

@onevent:preventDefault does not trigger when event is not already registered #18449

@poke

Description

@poke

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.

Metadata

Metadata

Assignees

Labels

Pillar: Technical DebtPriority:2Work that is important, but not critical for the releaseaffected-fewThis issue impacts only small number of customersarea-blazorIncludes: Blazor, Razor ComponentsbugThis issue describes a behavior which is not expected - a bug.feature-blazor-component-modelAny feature that affects the component model for Blazor (Parameters, Rendering, Lifecycle, etc)severity-minorThis label is used by an internal tool

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions