Web Component with progressive enhancements for the HTML <dialog> element
npm install @webfactoryde/dialog-utils
The <dialog-utils>
Web Component is meant to be a lightweight wrapper and progressive enhancement for <dialog>
elements that are used as modal dialogs.
The enhancements are:
autoopen
: The Web Component supports opening a dialog immediately if anautoopen
attribute is present on<dialog-utils>
.commandfor
andcommand
: The Web Component polyfills the Invoker Commands API to enable future-friendly, declarative linkup of buttons to show and close the dialog even in browsers that don't support the API yet. You can opt out of this if you prefer to write your own JavaScript logic to handle this functionality.closedby="any"
: The Web Component polyfills the declarative attribute for light dismissal of the dialog by a click outside of it.- Playing media: If the dialog contains an iframe, the Web Component will ensure that any media stops playing when the dialog is closed.
- Focus behaviour: You should use the declarative
autofocus
attribute to indicate whether the dialog itself or a specific interactive child element should receive focus when the dialog is shown. If this is not an option, the Web Component accepts aautofocus-target
attribute with a valid DOM selector string as its value. The WC will then try to set theautofocus
attribute on the first element that matches the selector.
- The JS file "dialog-utils.js" must be loaded. Depending on browser support requirements, transpilation for older browsers is recommended.
- Wrap your
<dialog>
with<dialog-utils>
. - Add a trigger and close
<button>
with your desired markup (e.g. nested icon, attributes, translated text, etc.). The buttons need to be made identifiable withcommandfor
andcommand
as per the specification, if you want to benefit from the ease-of-use polyfills. The Web Component leaves positioning and aesthetics of the buttons to the outside context.
<button commandfor="my-dialog" command="show-modal">Open my dialog</button>
<dialog-utils>
<dialog id="my-dialog>
<button commandfor="my-dialog" command="close">Close</button>
<h1>My modal</h1>
<p>Some content</p>
</dialog>
</dialog-utils>