<dialog>: The Dialog element
The <dialog> HTML element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow.
Attributes
This element includes the global attributes.
Warning: The tabindex attribute must not be used on the <dialog> element.
Indicates that the dialog is active and can be interacted with. When the open attribute is not set, the dialog shouldn’t be shown to the user. It is recommended to use the .show() or .showModal() methods to render dialogs, rather than the open attribute. If a <dialog> is opened using the open attribute, it will be non-modal.
Accessibility considerations
The native HTML <dialog> element should be used in creating modal dialogs as it provides usability and accessibility features that must be replicated if using other elements for a similar purpose. Use the appropriate .showModal() or .show() method to render dialogs. If creating a custom dialog implementation, ensure all expected default behaviors are supported and proper labeling recommendations are followed.
When implementing a dialog, it is important to consider the most appropriate place to set user focus. Explicitly indicating the initial focus placement by use of the autofocus attribute will help ensure initial focus is set to the element deemed the best initial focus placement for any particular dialog. When in doubt, as it may not always be known where initial focus could be set within a dialog, particularly for instances where a dialog’s content is dynamically rendered when invoked, then if necessary authors may decide focusing the <dialog> element itself would provide the best initial focus placement. When using HTMLDialogElement.showModal() to open a <dialog> , focus is set on the first nested focusable element.
Ensure a mechanism is provided to allow users to close a dialog. The most robust way to ensure all users can close a dialog is to include an explicit button to do so. For instance, a confirmation, cancel or close button as appropriate. Additionally, for those using a device with a keyboard, the Escape key is commonly expected to close modal dialogs as well. By default, a <dialog> invoked by the showModal() method will allow for its dismissal by the Escape . A non-modal dialog does not dismiss via the Escape key by default, and depending on what the non-modal dialog represents, it may not be desired for this behavior. If multiple modal dialogs are open, Escape should only close the last shown dialog. When using <dialog> , this behavior is provided by the browser.
The <dialog> element is exposed by browsers similarly to custom dialogs using the ARIA role=»dialog» attribute. <dialog> elements invoked by the showModal() method will have an implicit aria-modal=»true», whereas <dialog> elements invoked by the show() method, or rendered by use of the open attribute or changing the default display of a <dialog> will be exposed as [aria-modal=»false»] . When implementing modal dialogs, everything other than the <dialog> and its contents should be rendered inert using the inert attribute. When using <dialog> along with the HTMLDialogElement.showModal() method, this behavior is provided by the browser.
Usage notes
-
elements can close a <dialog> if they have the attribute method=»dialog» or if the button used to submit the form has formmethod=»dialog» set. In this case, the state of the form controls are saved, not submitted, the <dialog> closes, and the returnValue property gets set to the value of the button that was used to save the form’s state.
- The ::backdrop CSS pseudo-element can be used to style the backdrop that is displayed behind a <dialog> element when the dialog is displayed with HTMLDialogElement.showModal() . For example, to dim unreachable content behind the modal dialog.
Examples
Simple example
The following will render a non-modal, or modal-less, dialog. The «OK» button allows the dialog to be closed when activated.
Result
Because this dialog was opened via the open attribute, it is non-modal. In this example, when the dialog is dismissed, no method is provided to re-open it. Opening dialogs via HTMLDialogElement.show() is preferred over the toggling of the boolean open attribute.
Advanced example
This example opens a modal dialog when the «Show the dialog» button is activated. The dialog contains a form with a <select> and two <button> elements which default to type=»submit» . Updating the value of the <select> updates the value of the «confirm» button. This value is the returnValue . If the dialog is closed with the Esc key, there is no return value. When the dialog is closed, the return value is displayed under the «Show the dialog» button.
How TO — CSS/JS Modal
Learn how to create a Modal Box with CSS and JavaScript.
How To Create a Modal Box
A modal is a dialog box/popup window that is displayed on top of the current page:
Modal Header
Modals are awesome!
Step 1) Add HTML:
Example
<!— Trigger/Open The Modal —>
<button >Open Modal</button>
The <span> element with class=»close» should be used to close the modal.
Step 2) Add CSS:
Example
/* The Modal (background) */
.modal <
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
>
/* Modal Content/Box */
.modal-content <
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
>
/* The Close Button */
.close <
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
>
.close:hover,
.close:focus <
color: black;
text-decoration: none;
cursor: pointer;
>
The .modal class represents the window BEHIND the actual modal box. The height and width is set to 100%, which should create the illusion of a background window.
Add a black background color with opacity.
Set position to fixed; meaning it will move up and down the page when the user scrolls.
It is hidden by default, and should be shown with a click of a button (we’ll cover this later).
The .modal-content class
This is the actual modal box that gets focus. Do whatever you want with it. We have got you started with a border, some padding, and a background color. The margin: 15% auto is used to push the modal box down from the top (15%) and centering it (auto).
We also set the width to 400px — this could be more or less, depending on screen size. We will cover this later.
The .close class
The close button is styled with a large font-size, a specific color and floats to the right. We have also added some styles that will change the color of the close button when the user moves the mouse over it.
Step 3) Add JavaScript:
Example
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById(«myBtn»);
// Get the <span> element that closes the modal
var span = document.getElementsByClassName(«close»)[0];
// When the user clicks on the button, open the modal
btn.onclick = function() <
modal.style.display = «block»;
>
// When the user clicks on <span> (x), close the modal
span.onclick = function() <
modal.style.display = «none»;
>
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) <
if (event.target == modal) <
modal.style.display = «none»;
>
>
Add Header and Footer
Add a class for modal-header, modal-body and modal-footer:
Example
Style the modal header, body and footer, and add animation (slide in the modal):
Example
/* Modal Header */
.modal-header <
padding: 2px 16px;
background-color: #5cb85c;
color: white;
>
/* Modal Body */
.modal-body
/* Modal Footer */
.modal-footer <
padding: 2px 16px;
background-color: #5cb85c;
color: white;
>
/* Modal Content */
.modal-content <
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
animation-name: animatetop;
animation-duration: 0.4s
>
Bottom Modal («Bottom sheets»)
An example on how to create a full-width modal that slides in from the bottom:
Элемент HTML5 dialog
Давным давно, в спецификацию HTML5 был введён некий элемент, вернее его реинкарнация, решающая проблему диалоговых и модальных окон, которые все мы так любим использовать на различных сайтах. Но, к сожалению, я настолько был так рад его появлению, что даже не заметил этого события. Хотя потеря и не велика для нынешнего положения браузерных дел — раз элемент есть, нужно с ним разобраться.
Поддержка браузерами
Вместо тысячи слов:

Нет, это не два моих любимых браузера и не нужно искать какой-то скрытый смысл тут — это всего лишь те браузеры, которые за год (почти год) научились поддерживать данный элемент.
Конечно, если вы пришли из будущего или этой статье уже не первый день, то проверить какие браузеры уже научились поддерживать этот элемент можно посмотреть тут.
Поле для экспериментов получается у нас небольшое. Жаль.
Уходя от горьких нот в части введения и поддержки браузерами, давайте перейдём к самому интересному — практике.
Разметка
Раньше диалоговые и модальные окна верстались примерно так:
Сейчас же это делается немного иначе:
Отличий не так много, но они существенны:
- Элемент скрыт по умолчанию.
- Поддерживается семантическая вёрстка внутри элемента <dialog> .
Если добавить к элементу атрибут open , то перед нами предстанет само диалоговое окно:

Мне такой вид совсем не улыбается и работать с таким «красавцем» мне не хочется. Давайте приукрасим наш элемент:

В данной статье речь идёт не об умении использовать CSS, поэтому стили диалогового окна вы можете написать сами или посмотреть по ссылкам на jsFiddle прилагаемым к каждому пункту 🙂
Франкенштейн
Для того, чтобы наш элемент был полезным, его нужно оживить. Поможет нам в этом интерфейс элемента <dialog> . В этом разделе статьи мы обговорим теорию использования элемента.
И перед тем, как начать говорить о методах и свойствах, которые предоставляет нам API, нужно расставить все точки над понятием диалогового и модального окна:
Диалоговое окно
Диалоговым окном называют такое окно, которое временно появляется поверх приложения (в нашем случае сайта) и запрашивает и/или предоставляет различную информацию.
Модальное окно
Модальным окном называют такое диалоговое окно, которое блокирует работу пользователя с родительским приложением (в нашем случае сайта) до тех пор, пока пользователь это окно не закроет.
Благодаря интерфейсу HTMLDialogElement , который несёт в себе несколько свойств, методов и событий, мы сможем управлять нашим диалогом. Рассмотрим этот интерфейс подробнее.
Методы
Нам доступны три метода, которые позволяют:
- show() — Открыть диалоговое окно.
- showModal() — Открыть модальное окно.
- close() — Закрыть окно.
Свойства
В свойствах тоже нет большого разнообразия:
- returnValue — Возвращаемое значение, которое можно передать в close() .
- open — Логическое значение. Если true, то окно показано, если false, то окно скрыто.
События
А тут у нас всё ещё хуже:
- close — Событие закрытия окна.
Разное
Помимо основных методов и свойств, элемент <dialog> также поддерживает:
- form[method="dialog"] — Интеграция с формы с элементом. Действует только внутри диалогового и модального окна.
- autofocus — Перемещение фокуса на элемент управления формой внутри окна.
- cancel — Закрытие окна при нажатии кнопки Esc .
Маловато будет! Перейдём к примерам работы.
Реализация
Давайте попробуем реализовать диалоговые и модальные окна и их взаимодействие с окружающими и внутренними элементами.
Для примеров я буду использовать библиотеку Zepto.
Zepto
Библиотека Zepto по своей сути является аналогом всем известной библиотеки jQuery. Основное отличие заключается в поддержке браузеров и некотором несущественном расхождении в API.
Вот именно сейчас в вас может заиграть желание сетовать на отсутствие ванильного JavaScript в примерах, однако поспешу вас разочаровать — камнем преткновения для нас с вами будет сайт «You Might Not Need jQuery», на котором вы сможете посмотреть реализацию используемых плюшек библиотеки Zepto на ванильном JavaScript. Не думаю, что эта процедура займёт у вас уйму времени. Мне же библиотека даст возможность обратить немного больше внимания на интерфейс HTMLDialogElement , чем на реализацию некоторых побочных функций.
Открытие и закрытие диалогового окна.
Для того, чтобы работать со многими диалоговыми окнами как раз и были введены атрибуты data-tools и data-target .
Открытие и закрытие модального окна. Затемнение.
Работа с модальными окнами полностью повторяет таковую с диалоговым окном с той лишь разницей, что метод show() заменяется на showModal .
Теперь наше окно выглядит иначе:

Кратко об изменениях:
- Центрирование не только по горизонтали, но и по вертикали.
- Окно отбрасывает на всю страницу фон.
- Пользователь не может взаимодействовать с объектами на странице, отличными от объектов самого окна.
Управлять «тенью» можно с помощью CSS, используя псевдоэлемент ::backdrop :
Для примера, я изменил цвет затемнения на синий:

Возвращение значения из модального или диалогового окна.
Для передачи значения мы будем использовать метод close() и событие закрытия close .
После закрытия модального или диалогового окна, будь это событие нажатия на кнопку закрытия или нажатие клавиши Esc , будет отображено введённое значение:

Разумеется, что картинка «фотошоп» для наглядности, так как alert появился после закрытия модального окна.
Интеграция формы в диалоговое или модальное окно
Как уже говорилось ранее, интерфейс HTMLDialogElement предполагает наличие отдельного метода для управления диалоговым и модальным окном c помощью формы.
Немного изменим нашу разметку:
Теперь наше модальное окно выглядит так:

Осталось только слегка поменять наш скрипт. Нам нужно избавиться от обработчика кнопки закрытия окна и обработать возвращаемое значение.
Вот и всё! Соизвольте наслаждаться полученным результатом:

Спасение от Google
К сожалению, как и говорилось в самом начале статьи — поддержка браузерами у элемента скудная и не соответствует реалиям. Исправить это досадное положение призван полифил от команды Google Chrome, который добавляет полную поддержку данного элемента во все браузеры.
Для его использования необходимо подключить к странице сам полифил (CSS и JS) и, скажем так, активировать его:
При всём этом, затемнение фона так же поддерживается. Всего лишь нужно заменить конструкцию вида:
Деликатное решение проблемы 🙂
Вывод
Использовать элемент <dialog> можно уже сейчас (если вам не мешает лишний полифил), однако, стоит обратить внимание на рациональность этого решения в вашем проекте.
Помимо всех удобств, что мы уже рассмотрели на примерах в статье, есть ещё одно, которое позволяет не придерживаться идеологии z-index для диалоговых и модальных окон — Стек «верхнего слоя». Браузер сам заботится о том, что последнее вызванное вами окно будет находиться поверх всех остальных и его не перекроет какой-либо другой элемент.
Читайте новостные порталы по тематике веб-разработки, причём регулярно и не только на хорошо известных вам языках.
Делимся на оплату хостинга или кофе.
Чем чаще пью кофе, тем чаще пишу статьи.
<dialog>¶
Тег <dialog> (от англ. dialog — диалог) задает диалоговое окно, в котором можно выводить сообщение или форму, например, для входа на сайт.
Диалоговое окно отображается со следующим предустановленным стилем.
Таким образом диалоговое окно отображается с белым фоном, чёрной рамкой и по центру горизонтальной оси. Ширина совпадает с шириной родительского контейнера.
Для отображения и сокрытия диалогового окна применяются, соответственно, методы show() и hide() , как показано в примере ниже. Кроме того, диалог можно превратить в модальное окно, используя вместо show() метод showModal() . В этом случае остальные элементы на странице блокируются — текст нельзя выделить, а кнопки нажать до тех пор, пока диалоговое окно не будет закрыто. Также модальное окно можно закрыть клавишей Esc .