diff --git a/knowledge-base/dialog-close-on-esc.md b/knowledge-base/dialog-close-on-esc.md new file mode 100644 index 000000000..a3e87e25b --- /dev/null +++ b/knowledge-base/dialog-close-on-esc.md @@ -0,0 +1,78 @@ +--- +title: How to Close the Dialog on ESC When its Content is Focused +description: Learn how to enable closing the Dialog on ESC key after focusing the content by adding a focusable wrapper. +type: how-to +page_title: How to Close the Dialog on ESC When its Content is Focused +tags: blazor, dialog, keyboard +slug: dialog-kb-close-on-esc +--- + +## Description + +This knowledge base article answers to the following questions: + +* How to make Dialog responsive to keyboard events when content is clicked? +* Why doesn't ESC key work after clicking inside Dialog content? +* How to maintain keyboard functionality in Dialog after focus changes? + +When you click or focus inside the Dialog content area, the focus moves away from the Dialog component. As a result, the Dialog does not receive keyboard events, and pressing the `ESC` key does not close it. This behavior occurs because the keydown events are not invoked for the Dialog when the focus is on another element or the body tag. + +## Solution + +To ensure the Dialog closes on `ESC` even after focusing the content, wrap the Dialog content in a `div` with `tabindex="0"`. This makes the content wrapper focusable and allows keyboard events to be captured. Add custom styling to handle the focus state and preserve the existing content padding. + +>caption Example of Implementing a Focusable Wrapper with Visual Indication + +````RAZOR + + +
+

Click anywhere in this content area, then press ESC to close the dialog.

+
+
+ + Close + +
+ +Open Dialog + + + +@code { + private bool DialogVisible { get; set; } = true; + private string SampleText { get; set; } = string.Empty; + + private void OpenDialog() + { + DialogVisible = true; + } + + private void CloseDialog() + { + DialogVisible = false; + } +} +````