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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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 Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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),

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor