search
HomeWeb Front-endJS TutorialHow to Use the HTMLlt;dialog> Element

In frontend development, building or using pre-built UI components is a common task. However, these components often come with limitations. They are typically tied to specific frameworks and require complex, non-standardized logic. For a long time, basic UI components like dialog windows relied on custom implementations or, in more simple cases, built-in JavaScript methods such as alert(), prompt(), and confirm().

The great news is that you can now implement this component using the native

HTML element, which is part of the HTML5 standard and fully supported by all modern browsers.

The

HTML tag, introduced in May 2013 as part of a W3C working draft, was launched together with interactive elements like
and to address common UI challenges. Released in 2014, was initially supported only in Google Chrome and Opera. Full support for in Firefox and Safari came only in March 2022, delaying its adoption in production projects. However, with over two years of support from major browsers, the element is now stable enough to replace custom

Let's explore the features of

in more detail.

Core aspects of usage

The HTML

tag creates a hidden by default dialog box that can work as either a popup or a modal window.

Popups are frequently used to display simple notifications, such as cookie messages, disappearing toast alerts, tooltips, or right-click context menu elements.

Modal windows help users focus on specific tasks, such as notifications and warnings requiring user confirmation, complex interactive forms, and lightboxes for images or videos.

Popups don't prevent interaction with the page, while modal windows overlay the document, dim the background, and block other actions. This behavior works without additional styles or scripts; the only difference is the method used to open the dialog.

Dialog window opening methods

— popup:

<dialog>





<pre class="brush:php;toolbar:false">const popUpElement = document.getElementById("pop-up");

popUpElement.show();

— modal window:

<dialog>





<pre class="brush:php;toolbar:false">const modalElement = document.getElementById("modal");

modalElement.showModal();

In both cases, opening the

tag sets its open attribute to true. Setting it directly will open the dialog as a popup, not a modal. To render modal windows, you must use the appropriate method. No JavaScript is needed to create an initially opened popup.

<dialog open>Hi, I'm a popup!</dialog>

Try it out:

  • Opening a popup using the .show() method: https://codepen.io/alexgriss/pen/zYeMKJE
  • Opening a modal window using the .showModal() method: https://codepen.io/alexgriss/pen/jOdQMeq
  • Directly changing the open attribute: https://codepen.io/alexgriss/pen/wvNQzRB

Dialog window closing approaches

Dialog windows close the same way, no matter how they were opened. Here are a few ways to close a popup or modal window:

— with the .close() method:

<dialog>





<pre class="brush:php;toolbar:false">const popUpElement = document.getElementById("pop-up");

popUpElement.show();

— by triggering the submit event in a form with the method="dialog" attribute:

<dialog>





<pre class="brush:php;toolbar:false">const modalElement = document.getElementById("modal");

modalElement.showModal();

— by pressing the Esc key:

Closing with Esc works for modal windows only. It first triggers the cancel event, then close, making it easy to warn users about unsaved changes in forms.

Try it out:

  • Closing a dialog box with the close method: https://codepen.io/alexgriss/pen/GRzwjaV
  • Closing a dialog box through the submit form: https://codepen.io/alexgriss/pen/jOdQVNV
  • Closing a modal window with the Esc key: https://codepen.io/alexgriss/pen/KKJrNKW
  • Preventing a modal window from closing with Esc: https://codepen.io/alexgriss/pen/mdvQObN

Return value on close

When closing a dialog with a form using the method="dialog" attribute, you can capture the value of the submit button. This is useful if you want to trigger different actions based on the button clicked. The value is stored in the returnValue property.

Try it out: https://codepen.io/alexgriss/pen/ZEwmBKx

A closer look at how it works

Let's dive deeper into the mechanics of the dialog window and the details of its browser implementation.

The mechanics of a popup

Opening a

as a popup with .show() or the open attribute automatically positions it with position: absolute in the DOM. Basic CSS styles, like margins and borders, are applied to the element, and the first focusable item inside the window will automatically get focus through the autofocus attribute. The rest of the page remains interactive.

The mechanics of a modal window

A modal window is designed and works in a more complex way than a popup.

Document overlaying

When opening a modal window with .showModal(), the

element is rendered in a special HTML layer that covers the entire visible area of the page. This layer is called the top layer and is controlled by the browser. In some browsers like Google Chrome, each modal is rendered in a separate DOM node within this layer, visible in the element inspector.

How to Use the HTMLlt;dialog> Element

The concept of layers refers to the stacking context, which defines how elements are positioned along the Z-axis relative to the user. Setting a z-index value in CSS creates a stacking context for an element, where the position of its children is calculated within that context. Modal windows are always at the top of this hierarchy, so no z-index is needed.

Learn more about the stacking context on MDN.

To learn more about the elements rendered in the top layer, visit MDN.

Document blocking

When a modal element is rendered in the top layer, a ::backdrop pseudo-element is created with the same size as the visible document area. This backdrop prevents interaction with the rest of the page, even if pointer-events: none CSS rule is set.

The inert attribute is automatically set for all elements except the modal window, blocking user actions. It disables click and focus events and makes the elements inaccessible to screen readers and other assistive technologies.

Learn more about the inert attribute on MDN.

Focus behavior

When the modal opens, the first focusable element inside it automatically gets focus. To change the initially focused element, you can use the autofocus or tabindex attributes. Setting tabindex for the dialog element itself isn't possible, as it's the only element on the page where inert logic doesn't apply.

After the dialog is closed, the focus returns to the element that opened it.

Solving UX problems with modal windows

Unfortunately, the native implementation of the

element doesn't cover all aspects of interacting with modal windows. Next, I'd like to go over the main UX issues that may come up when using modal windows and how to solve them.

Scroll blocking

Even though the native HTML5 modal window creates a ::backdrop pseudo-element that blocks interaction with the content underneath it, the page scroll is still active. This can be distracting for users, so it's recommended to cut off the content of the body when the modal opens:

<dialog>





<pre class="brush:php;toolbar:false">const popUpElement = document.getElementById("pop-up");

popUpElement.show();

Such a CSS rule will have to be dynamically added and removed each time the modal window is opened and closed. This can be achieved by manipulating a class containing this CSS rule:

<dialog>





<pre class="brush:php;toolbar:false">const modalElement = document.getElementById("modal");

modalElement.showModal();

You can also use the :has selector if its support status meets the project's requirements.

<dialog open>Hi, I'm a popup!</dialog>

Try it out: https://codepen.io/alexgriss/pen/XWOyVKj

Closing the dialog by clicking outside the window

This is a standard UX scenario for a modal window and it can be implemented in several ways. Here are two ways to solve this problem:

A method based on the behavior of the ::backdrop pseudo-element

Clicking on the ::backdrop pseudo-element is considered a click on the dialog element itself. Therefore, if you wrap the entire content of the modal window in an additional

and then cover the dialog element itself, you can determine where the click was directed — on the backdrop or on the modal window content.

Don't forget to reset the browser's default padding and border styles for the

element to prevent the modal window from closing on accidental clicks:

<dialog>





<pre class="brush:php;toolbar:false">const popUpElement = document.getElementById("pop-up");

popUpElement.show();

Now, we apply the common styles for the modal window's borders and margins only to the inner wrapper.

We need to write a function that will close the modal window only when clicking on the backdrop, not on the inner wrapper element:

<dialog>





<pre class="brush:php;toolbar:false">const modalElement = document.getElementById("modal");

modalElement.showModal();

Try it out: https://codepen.io/alexgriss/pen/mdvQXpJ

A method based on determining the size of the dialog window

This method is different from the first one, which needed an extra wrapper for the modal content. Here, you don't need any extra wrapping. All that's required is to check if the cursor's position goes outside the element's area when clicked:

<dialog open>Hi, I'm a popup!</dialog>

Try it out: https://codepen.io/alexgriss/pen/NWoePVP

Styling the dialog window

The

element is more flexible in terms of styling than many native HTML elements. Here are some examples to style dialog windows:

Styling the backdrop using the ::backdrop selector: https://codepen.io/alexgriss/pen/ExrOQEO

Animated dialog window opening and closing: https://codepen.io/alexgriss/pen/QWYJQJO

Modal window as a sidebar: https://codepen.io/alexgriss/pen/GRzwxgr

Accessibility

For a long time, the

element had some accessibility problems, but now it works well with major assistive technologies like screen readers (VoiceOver, TalkBack, NVDA).

When a

is opened, the focus is moved to the dialog by the screen reader. For modal windows, the focus remains within the dialog until it is closed.

By default, the

element is recognized by assistive technologies as having the ARIA attribute role="dialog". A modal dialog will be recognized as having the ARIA attribute aria-modal="true".

Here are some ways to improve the accessibility of the

element:

aria-labelledby

Always include a title inside dialog windows and specify the aria-labelledby attribute for the

element, with the value set to the id of the title.

<dialog>





<pre class="brush:php;toolbar:false">const popUpElement = document.getElementById("pop-up");

popUpElement.show();

If you need to style the ::backdrop pseudo-element, ensure you also apply those styles to the corresponding .backdrop element to ensure compatibility with older browsers:

<dialog>





<pre class="brush:php;toolbar:false">const modalElement = document.getElementById("modal");

modalElement.showModal();

It's recommended to connect the polyfill via a dynamic import and only for browsers that don't support the

element:

<dialog open>Hi, I'm a popup!</dialog>

Conclusion

The native HTML5

element is a relatively simple yet powerful tool for implementing modal windows and popups. It's well supported by modern browsers and can be successfully used in projects based on both vanilla JS and any frontend framework.

In this article, we discussed the following topics:

  • Problems the element solves;
  • Interaction with the element's API;
  • How dialog windows work at the browser level;
  • Common issues with modals and their solutions;
  • Improving accessibility of the element for assistive technologies like screen readers;
  • Expanding browser support for the element.

Finally, I invite you to check out the modal window component implementation in pure JS, which takes into account the main aspects discussed in the article: https://codepen.io/alexgriss/pen/abXPOPP

That's all I wanted to share about working with the

HTML element. I hope this article inspires you to experiment!

The above is the detailed content of How to Use the HTMLlt;dialog> Element. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools