I am in the process of developing a tooltip feature within the Blazor framework. The main goal I have is to make the tooltip disappear when the escape key is pressed while focusing on the button.
Currently, I have successfully implemented this feature using the provided code. However, it involves JavaScript, which I would like to avoid if possible.
This is my current approach:
@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>