Reputation: 133
I'm having a bit of trouble implementing an @onkeydown event on a Blazor component. The event is located on a table header to provide a keyboard alternative to the @onclick "sort" event. The @onclick event works just fine, but the @onkeydown event doesn't seem to do anything.
My code for the .razor file is
<thead>
<tr>
<th tabindex="0"><span role="button" aria-label="Sort by event name" @onkeydown="@((args) => KeyPressSort("EventDesc", args))" @onclick="@(() => Sort("EventDesc"))">Event Name</span><i class="@(SortIndicator("EventDesc"))"></i></th>
<th tabindex="0"><span role="button" aria-label="Sort by event start date" @onclick="@(() => Sort("EventStart"))">Event Start Time</span><i class="@(SortIndicator("EventStart"))"></i></th>
<th tabindex="0" class="d-none d-md-table-cell"><span role="button" aria-label="Sort by event end date" @onclick="@(() => Sort("EventEnd"))">Event End Time</span><i class="@(SortIndicator("EventEnd"))"></i></th>
<th class="d-none d-md-table-cell">User Name</th>
<th tabindex="0" class="d-none d-md-table-cell"><span role="button" aria-label="Sort by user email" @onclick="@(() => Sort("UserEmail"))">Student Email</span><i class="@(SortIndicator("UserEmail"))"></i></th>
<td></td>
</tr>
</thead>
The code for the .cs file is:
protected async Task KeyPressSort(string sortField, KeyboardEventArgs e)
{
if (e.Code == "Enter" || e.Code == "NumpadEnter")
{
await Sort(sortField);
}
}
I've put a breakpoint at the if statement in the KeyPressSort method but, even after tabbing over the table header and pressing the enter key, it is never hit.
Can anyone see what's wrong here? I suspect it's something to do with the span not being an input element but other than giving it a role of button I'm not sure what else to do.
Thanks for any help!
Upvotes: 0
Views: 1560
Reputation: 30167
You can't have key press events on an element that can't receive focus. If you can't tab to the element then it can't receive focus. Mouse clicks are OK, there's no focus involved. If you want to do what you're doing then you need to make it something like a button and style it appropriately.
Upvotes: 1