I'm currently developing a tooltip component in the Blazor framework. The functionality I'm trying to achieve is for the tooltip to disappear when the escape key is pressed while the button is focused.
I've managed to implement this functionality with the following code, but it relies on JavaScript, which I'd prefer to avoid if possible.
Here's my current implementation
@inject IJSRuntime JSRuntime<button @onclick="ToggleTooltip">test</button><div role="tooltip" @ref="tooltip" tabindex="0" @onkeydown="CloseTooltip"> Password Rules:</div><p>test</p>@code { ElementReference tooltip; bool showTooltip = false; void ToggleTooltip() { showTooltip = !showTooltip; if (showTooltip) { tooltip.FocusAsync(); } } async Task CloseTooltip(KeyboardEventArgs e) { if (e.Key == "Escape") { showTooltip = false; await JSRuntime.InvokeVoidAsync("Blurred", tooltip); await InvokeAsync(StateHasChanged); } }}<script> window.Blurred = function(element) { element.blur();};</script><style> * { margin: 0; padding: 0; } [role="tooltip"] { margin-top: .75rem; display: none; position: absolute; background: black; color: white; } [role="tooltip"]:before { margin-top: -7px; content: ""; border: 7px solid transparent; border-bottom-color: #000; border-top-width: 0; position: absolute; } button:hover + [role="tooltip"], button:focus + [role="tooltip"], [role="tooltip"]:focus { display: block; }</style>